Top Questions

  • 5.11 Years

    • Category : Php
    • Location : Chandigarh, India
    • Posted On : Nov 23, 2017

    There's a bug in Wordpress 4.9, I discovered this temporary super code. I plan on uninstalling it once they fix the bug, but it works great in the meantime!

    global $wpdb;
    $wpdb->query( "DELETE FROM `$wpdb->options` WHERE `option_name` LIKE '_transient_files_%' LIMIT 1" );
     
  • 5.11 Years

    • Category : Php
    • Location : Chandigarh, India
    • 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 : Chandigarh, India
    • 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 : Chandigarh, India
    • 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");
     
  • 2.9 Years

    • Category : Php
    • Location : Chandigarh
    • Posted On : Sep 15, 2017

    Using this code you can upload and image using curl with third party role

    
       /*Send Page*/
    
       $filename = covertImage($filename);
       
       $fields = array(
                            'customer_name' => 'Gulshan Sharma',
                            'filename' => $filename,
    
                    );
                    $ch = curl_init();
                    curl_setopt($ch, CURLOPT_URL,'http:example.com/upload/');
                    curl_setopt($ch, CURLOPT_POST, 1);
                    curl_setopt($ch, CURLOPT_USERAGENT, "webapp");
                    //curl_setopt($ch, CURLOPT_POSTFIELDS,$fields);
    
                    // in real life you should use something like:
                    curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($fields));
                    // receive server response ...
                    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
                    curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
                    curl_setopt($ch, CURLOPT_USERPWD, "xxx:xxx"); 
                    $server_output = curl_exec ($ch);
                    curl_close ($ch);
    
      function covertImage($path){
    
                $type = pathinfo($path, PATHINFO_EXTENSION);
                $data = file_get_contents($path);
                $base64 = 'data:image/' . $type . ';base64,' . base64_encode($data);
                return $base64;
       }
     /*RecivePage*/
    
       $filename = base64_to_jpeg($_POST['filename']);
       
       echo $filename;
       
       function base64_to_jpeg($base64_string) {
                         $upload_path = '/hosted-libraries/temp/';
                        $upload_path = $_SERVER['DOCUMENT_ROOT'] . $upload_path;
                        $newImg = uniqid();
                        $img = str_replace('data:image/png;base64,', '', $base64_string);
                        $img = str_replace(' ', ' ', $img);
                        $data = base64_decode($img);
                        $file = $upload_path . $newImg . '.png';
                        $success = file_put_contents($file, $data);
                        if($success)
                            return $file;
                        else
                            FALSE;
                       
         }
  • 2.9 Years

    • Category : Jquery
    • Location : Chandigarh
    • Posted On : Aug 31, 2017

    Using this module you can hide requested parameters from inspect element

    var http = new XMLHttpRequest();
    var url = "Url Path";
    var params ='Your parameters';
    http.open("GET", url, true);
    
    //Send the proper header information along with the request
    http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    
    http.onreadystatechange = function() {//Call a function when the state changes.
        if(http.readyState == 4 && http.status == 200) {
            console.log(http.responseText);
        }
    http.send(params);
    }
     
  • 5.11 Years

    • Category : Php
    • Location : Chandigarh, India
    • 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 : Chandigarh, India
    • 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 : Chandigarh, India
    • 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--------
  • 2.9 Years

    • Category : Wordpress
    • Location : Chandigarh
    • Posted On : Jun 26, 2017

    Create custom menu and sub-menu in worpress

    add_action('admin_menu', 'main_menu');
    function main_menu()
    {
       add_menu_page( 'Setting' , 'Setting' , 'manage_options' , __FILE__ , 'setting');
       add_submenu_page( __FILE__ , 'Submenu1', 'Submenu1' , 'manage_options' , __FILE__ . 'Submenu1' , 'Submenu1');
    }
    
    /* Menu*/
    
    function Submenu1(){
    	echo "Submenu1 Page";
    }
    
    /* Sub Menu*/
    
    function setting(){
    	echo "Setting Page";
    }