Vikas Pandey@vikas

I am the best

  • 5.11 Years

    • Category : Php
    • Location : Mohali
    • Posted On : Nov 6, 2017

    To load a .js or .css file dynamically, in a head section, it means using DOM methods to first create a new "SCRIPT" or "LINK" element, assign it the appropriate attributes, and finally, use element.appendChild() to add the element to the desired location within the document tree. It sounds a lot more fancy than it really is. Lets see how it all comes together

    <script type="text/javascript">
    // function
    function loadheadfile(filename, filetype){
    	if(filetype=="js"){
    		var fileref=document.createElement('script')
    		fileref.setAttribute("type","text/javascript")
    		fileref.setAttribute("src", filename)
    	}
    	else if(filetype=="css") {
    		var fileref=document.createElement("link")
    		fileref.setAttribute("rel", "stylesheet")
    		fileref.setAttribute("type", "text/css")
    		fileref.setAttribute("href", filename)
    	}
    	if(typeof fileref!="undefined")
    		document.getElementsByTagName("head")[0].appendChild(fileref)
    }
    
    
    // call function
    loadheadfile('https://tsuyoshiwada.github.io/sweet-scroll/lib/icomoon/style.css','css');
    </script>
     
  • 5.11 Years

    • Category : Php
    • Location : Mohali
    • Posted On : Oct 7, 2017

    YouTube video Link may be encountered in a variety of formats:

    1.     latest short format: http://youtu.be/NLqAF9hrVbY
    2.     iframe: http://www.youtube.com/embed/NLqAF9hrVbY
    3.     iframe (secure): https://www.youtube.com/embed/NLqAF9hrVbY
    4.     object param: http://www.youtube.com/v/NLqAF9hrVbY?fs=1&hl=en_US
    5.     object embed: http://www.youtube.com/v/NLqAF9hrVbY?fs=1&hl=en_US
    6.     watch: http://www.youtube.com/watch?v=NLqAF9hrVbY
    7.     users: http://www.youtube.com/user/Scobleizer#p/u/1/1p3vcRhsYGo
    8.     ytscreeningroom: http://www.youtube.com/ytscreeningroom?v=NRHVzbJVx8I
    9.     any/subdomain/too: http://gdata.youtube.com/feeds/api/videos/NLqAF9hrVbY
    10.     more params: http://www.youtube.com/watch?v=spDj54kf-vY&feature=g-vrec
    11.     query may have dot: http://www.youtube.com/watch?v=spDj54kf-vY&feature=youtu.be
    12.     nocookie domain: http://www.youtube-nocookie.com
    function convertYoutube($string) {
    	$pattern='~(?#!js YouTubeId Rev:20160125_1800)
            # Match non-linked youtube URL in the wild. (Rev:20130823)
            https?://          # Required scheme. Either http or https.
            (?:[0-9A-Z-] \.)?  # Optional subdomain.
            (?:                # Group host alternatives.
              youtu\.be/       # Either youtu.be,
            | youtube          # or youtube.com or
              (?:-nocookie)?   # youtube-nocookie.com
              \.com            # followed by
              \S*?             # Allow anything up to VIDEO_ID,
              [^\w\s-]         # but char before ID is non-ID char.
            )                  # End host alternatives.
            ([\w-]{11})        # $1: VIDEO_ID is exactly 11 chars.
            (?=[^\w-]|$)       # Assert next char is non-ID or EOS.
            (?!                # Assert URL is not pre-linked.
              [?=& %\w.-]*     # Allow URL (query) remainder.
              (?:              # Group pre-linked alternatives.
                [\'"][^<>]*>   # Either inside a start tag,
              | </a>           # or inside <a> element text contents.
              )                # End recognized pre-linked alts.
            )                  # End negative lookahead assertion.
            [?=& %\w.-]*       # Consume any URL (query) remainder.
            ~ix';
    	preg_match_all($pattern,$string,$match);
    	$res=array();
    	$res['youtube']=$match;
    	$res['text']=preg_replace($pattern, '', $string);
    	return $res;
    }
    $text = "php find youtube link in string. How do I find all YouTube video ids in a string using a regex https://www.youtube.com/watch?v=ItTjUrTZ_JE Find youtube Link in PHP string and Convert it into embed code? Well, you need to filter out the youtube links first and put them into an string. Next you need to find out the youtube links of the url which is very easy. Use this script:";
    
    $all=convertYoutube($text);
    
    //print_r($all);
    
    echo $all['youtube'][1][0];	
    // ItTjUrTZ_JE
    
    echo $all['youtube'][0][0];	
    // https://www.youtube.com/watch?v=ItTjUrTZ_JE
    
    echo $all['text'];	
    // php find youtube link in string. How do I find all YouTube video ids in a string using a regex Find youtube Link in PHP string and Convert it into embed code? Well, you need to filter out the youtube links first and put them into an string. Next you need to find out the youtube links of the url which is very easy. Use this script:
    
  • 5.11 Years

    • Category : Wordpress
    • Location : Mohali
    • Posted On : Oct 5, 2017

    After wordpress login redirect page but not refresh so please try to add these lines in the top of the your wordpress theme file like header.php or wp-config.php

    header("Expires: Thu, 19 Nov 1981 08:52:00 GMT");
    header("Cache-Control: no-store, no-cache, must-revalidate");
     
  • 5.11 Years

    • Category : Php
    • Location : Mohali
    • Posted On : Aug 17, 2017

    MailChimp REST Api V3 exposes methods that allows you to add, change subscribed to unsubscribed, delete list member and get all member list of a specific MailChimp list.

    The following code snippet help you to add a new subscriber to MailChimp List.
    <?php
    $api_key = 'API_KEY';
    $list_id = 'LIST_ID';
    
    $dataCenter = substr($api_key,strpos($api_key,'-') + 1);
    $url = 'https://'.$dataCenter.'.api.mailchimp.com/3.0/lists/'.$list_id.'/members';
       $pfb_data = array(
        'email_address' => "YOUR_EMAIL_ID",
        'status'        => 'subscribed',
        'merge_fields'  => array(
          'FNAME'       => "YOUR_FIRST_NAME",
          'LNAME'       => "YOUR_LAST_NAME"
        ),
      );
    
    // connect and get results
    $result = json_decode( dorcode_mailchimp_curl_connect( $url, 'POST',$api_key, $pfb_data ) );
    
    if( $result->status == 400){
    	// error
       echo "already subscriber.";
    } elseif( $result->status == 'subscribed') {
    	// success
    	echo "subscribered";
    }
    ?>
    MailChimp change subscribed to unsubscribed.
    <?php
    $api_key = 'API_KEY';
    $list_id = 'LIST_ID';
    $email_to_unsubscribe = 'YOUR_EMAIL_ID';
    
    $dataCenter = substr($api_key,strpos($api_key,'-')+ 1);
    $url = 'https://'.$dataCenter.'.api.mailchimp.com/3.0/lists/'.$list_id.'/members/'.md5($email_to_unsubscribe);
    $result = json_decode(dorcode_mailchimp_curl_connect($url, 'PUT',$api_key, array('status'=>'unsubscribed')));
    if( $result->status == 400){
    	// error
        echo $result->errors[0]->message;
    } elseif( $result->status == 'unsubscribed') {
    	// success
        echo "unsubscribed";
    }
    ?>
    MailChimp delete list member.
    <?php
    $api_key = 'API_KEY';
    $list_id = 'LIST_ID';
    $email_to_unsubscribe = 'YOUR_EMAIL_ID';
    
    $dataCenter = substr($api_key,strpos($api_key,'-')+ 1);
    $url = 'https://'.$dataCenter.'.api.mailchimp.com/3.0/lists/'.$list_id.'/members/'.md5($email_to_unsubscribe);
    $result = json_decode(dorcode_mailchimp_curl_connect($url, 'DELETE',$api_key, array('status'=>'DELETE')));
    echo $result; // output "null"
    ?>
    MailChimp get all member list.
    <?php
    $api_key = 'API_KEY';
    $list_id = 'LIST_ID';
    
    $dataCenter = substr($api_key,strpos($api_key,'-')+ 1);
    $url = 'https://'.$dataCenter.'.api.mailchimp.com/3.0/lists/'.$list_id;
    $body = json_decode(dorcode_mailchimp_curl_connect($url,'GET',$api_key));
    
    // number of members in this list
    $member_count = $body->stats->member_count;
    $email = array();
     
    for( $offset = 0; $offset < ($member_count+50); $offset  = $offset+50 ) :
        $data = array(
            'offset' => $offset,
            'count'  => 50
        );
        // URL to connect
        $url = 'https://'.$dataCenter.'.api.mailchimp.com/3.0/lists/'.$list_id.'/members';
        // connect and get results
        $body = json_decode(dorcode_mailchimp_curl_connect($url, 'GET',$api_key, $data));
        foreach ( $body->members as $member ) {
        	// if($member->status=="subscribed") if you want to get members where status is subscribed
              $email[] = $member->email_address;
        }
    endfor;
    print_r($email);
    ?>
    MailChimp curl main php function.
    <?php
    function dorcode_mailchimp_curl_connect($url, $request_type, $api_key, $data = array()) {
    
    
        if( $request_type == 'GET' )
            $url .= '?' . http_build_query($data);
     
        $mch = curl_init();
        $headers = array(
            'Content-Type: application/json',
            'Authorization: Basic '.base64_encode( 'user:'. $api_key )
        );
        curl_setopt($mch, CURLOPT_URL, $url );
        curl_setopt($mch, CURLOPT_HTTPHEADER, $headers);
        //curl_setopt($mch, CURLOPT_USERAGENT, 'PHP-MCAPI/2.0');
        curl_setopt($mch, CURLOPT_RETURNTRANSFER, true); // do not echo the result, write it into variable
        curl_setopt($mch, CURLOPT_CUSTOMREQUEST, $request_type); // according to MailChimp API: POST/GET/PATCH/PUT/DELETE
        curl_setopt($mch, CURLOPT_TIMEOUT, 10);
        curl_setopt($mch, CURLOPT_SSL_VERIFYPEER, false); // certificate verification for TLS/SSL connection
     
        if( $request_type != 'GET' ) {
            curl_setopt($mch, CURLOPT_POST, true);
            curl_setopt($mch, CURLOPT_POSTFIELDS, json_encode($data)); // send data in json
        }
     
        return curl_exec($mch);
    }
    
    ?>
     
  • 5.11 Years

    • Category : Php
    • Location : Mohali
    • Posted On : Aug 11, 2017

    WordPress offers built-in functionality for navigating through posts. Theme developers can use simple default wordpress pagination function or other pagination function for better customize.

    // Create table in mysql
    CREATE TABLE `your_table_name` (
      `id` int(11) NOT NULL AUTO_INCREMENT,
      `title` varchar(200) NOT NULL,
      `addtime` int(20) NOT NULL,
      PRIMARY KEY (`id`)
    ) ENGINE=InnoDB DEFAULT CHARSET=latin1;
    
    // Insert table data
    INSERT INTO `your_table_name` (`id`, `title`, `addtime`) VALUES
    (1, 'test', 1299446702);	// addtime is timestamp
    
    
    
    <?php
    // insert this code where your want to add pagination
    // ----------- code start -----------
    
    $table_name =  "your_table_name"; 	// enter your table name
    $item_per_page=5;					// enter number 
    
    $all = $wpdb->get_row( "SELECT count(*) as total FROM {$table_name} WHERE 1=1", ARRAY_A );
    $page_number = (get_query_var('page')) ? get_query_var('page') : 1;
    $offset = ($page_number - 1) * $item_per_page;
    $data = $wpdb->get_results( "SELECT * FROM {$table_name} WHERE 1=1 ORDER BY id DESC LIMIT $offset,$item_per_page", ARRAY_A );
    $cou=$page_number*$item_per_page;
    ?>
    
    <h2>Results <?=$page_number ?>-<?=($cou>$all['total'])?$all['total']:$cou ?> of <?=$all['total'] ?></h2>
    <ul class="pagination">
    	<?php echo pagination($all['total'], $item_per_page, $page_number, site_url()."/your-page-name/?page=%d"); ?>
    </ul>
    
    
    <?php
    foreach ($data as $one) {
    ?>
    		<?=$one['id'] ?> <br />
    		<?=$one['title'] ?>
    <?php
    }
    ?>
    // ----------- code end -----------
    
    
    // add function.php in wordpress----------- code start ----
    
    function pagination($item_count, $limit, $cur_page, $link)
    {
           $page_count = ceil($item_count/$limit);
           $current_range = array(($cur_page-2 < 1 ? 1 : $cur_page-2), ($cur_page 2 > $page_count ? $page_count : $cur_page 2));
    
           // First and Last pages
           $first_page = $cur_page > 3 ? '<a href="'.sprintf($link, '1').'">1</a>'.($cur_page < 5 ? ', ' : ' ... ') : null;
           $last_page = $cur_page < $page_count-2 ? ($cur_page > $page_count-4 ? ', ' : ' ... ').'<a href="'.sprintf($link, $page_count).'">'.$page_count.'</a>' : null;
    
           // Previous and next page
           $previous_page = $cur_page > 1 ? '<a href="'.sprintf($link, ($cur_page-1)).'">&lt;&lt;</a>  ' : null;
           $next_page = $cur_page < $page_count ? '  <a href="'.sprintf($link, ($cur_page 1)).'">&gt;&gt;</a>' : null;
    
           // Display pages that are in range
           for ($x=$current_range[0];$x <= $current_range[1];   $x)
                   $pages[] = '<a href="'.sprintf($link, $x).'">'.($x == $cur_page ? '<strong>'.$x.'</strong>' : $x).'</a>';
    
           if ($page_count > 1)
                   return '<p class="pagination">'.$previous_page.$first_page.implode('&nbsp;&nbsp;', $pages).$last_page.$next_page.'</p>';
    }
    
    // add function.php in wordpress----------- code end ----
  • 5.11 Years

    • Category : Php
    • Location : Mohali
    • Posted On : Aug 10, 2017

    This article, aimed at plugin developers, describes how to add Ajax to a plugin or page. Before reading this article, you should be familiar with the following

    // function.php in Wordpress -------- Start Code--------
    add_action('wp_head', 'dorcode_ajaxurl');
    function dorcode_ajaxurl() {
       echo '<script type="text/javascript">
               var ajaxurl = "'.admin_url('admin-ajax.php').'";
            </script>';
    }
    
    
    add_action( 'wp_ajax_your_dorcode', 'my_dorcode' );
    add_action( 'wp_ajax_nopriv_your_dorcode', 'my_dorcode' );
    
    function my_dorcode() {
    	$data_id = intval( $_POST['data_id'] );
        echo $data_id;
        wp_die();
    }
    // function.php in Wordpress -------- End Code--------
    
    
    
    // Anywhere in Wordpress -------- Start Code--------
    
    // if you need
    var ajaxurl = "<?php echo admin_url('admin-ajax.php') ?>";
    jQuery(document).ready(function($) {
    	var data = {
    		'action': 'your_dorcode',
    		'data_id': 1525
    	};
    	jQuery.post(ajaxurl, data, function(response) {
    		alert('Got this from the server:' + response);
    	});
    
    });
    // Anywhere in Wordpress -------- End Code--------
  • 5.11 Years

    • Category : Wordpress
    • Location : Mohali
    • Posted On : Apr 11, 2017

    How to get WordPress Child Theme Path.

    When you create a website in wordpress, for this and take a theme and create a child theme.
    Ex. Parent Theme: dorcode
    Child Theme: dorcode-child

    So copy in the folder of the child a style.css and header.php, because you want to modify the header too. you modify the file of the child.

    In my style.css you add the line Template: with the name of the father theme


    // add this function to function.php and replace with get_template_directory_uri() to get_template_directory_child().
    function get_template_directory_child() {
        $directory_template = get_template_directory_uri(); 
        $directory_child = $directory_template.'-child';
        return $directory_child;
    }
     
  • 5.11 Years

    • Category : Wordpress
    • Location : Mohali
    • Posted On : Feb 9, 2017

    I have below code here. It's display that I want categories names with all details as well. This code to display top post categories first show.

    <?php
    $GLOBALS['uname'] = get_categories();
    define(_SYSTEM_, 'uname');
    class get_all_category_by_top_post {
        public function show() {
            $categories = $this->{_SYSTEM_};
            usort($categories,array($this,'sortByOrder'));
            return $categories;
        }
      public function sortByOrder($a, $b) {
         return $a->count < $b->count;
      }
        public function __get($d) {
            return $GLOBALS[$d];  
        }
    }
    $categories = new get_all_category_by_top_post();
    echo "<pre>";
    print_r($categories->show());
    ?>
  • 5.11 Years

    • Category : Php
    • Location : Mohali
    • Posted On : Jan 10, 2017

    If the strings are different [iframe] and [/iframe], take a look at this. copy his code below:

    <?php
    function get_string_between($string, $start, $end){
        $string = ' ' . $string;
        $ini = strpos($string, $start);
        if ($ini == 0) return '';
        $ini  = strlen($start);
        $len = strpos($string, $end, $ini) - $ini;
        return substr($string, $ini, $len);
    }
    $string='testing [iframe]dorcode.com[/iframe] test';
    $parsed = get_string_between($string, '[iframe]', '[/iframe]');
    echo $parsed; // output: dorcode.com
  • 5.11 Years

    • Category : Php
    • Location : Mohali
    • Posted On : Dec 10, 2016

    MySQL sorting by age if your birthday like this 1974-05-15, 1974-05-28 (YEAR,MONTH,DATE)

    <?php
    $table_name="YOUR_TABLE_NAME";
    $column_name="birthdate";
    $age_from=15;
    $age_to=45;
    
    $con=mysqli_connect("localhost","my_user","my_password","my_db");
    // Check connection
    if (mysqli_connect_errno())
      {
      echo "Failed to connect to MySQL: " . mysqli_connect_error();
      }
    
    // Perform queries
    
    $sql="SELECT * FROM $table_name WHERE TIMESTAMPDIFF(YEAR, $column_name, CURDATE()) BETWEEN $age_from AND $age_to";
    $result=mysqli_query($con,$sql);
    
    
    // Associative array
    $row=mysqli_fetch_array($result,MYSQLI_ASSOC);
    printf ("%s (%s)\n",$row["id"],$row["name"]);
    
    // Free result set
    mysqli_free_result($result);
    
    mysqli_close($con);
    ?>