Top Questions:

  • 5 years-11 months

    How to Add Pagination in Your WordPress Theme or Core Php

    • Category : php
    • Location : Chandigarh, India
    • Posted On :
    • Posted by : Vikas

    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 years-11 months

    how to use ajax in wordpress page

    • Category : php
    • Location : Chandigarh, India
    • Posted On :
    • Posted by : Vikas

    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--------
  • 3 years-4 months

    HTML5 GEO LOCATION

    • Category : jquery
    • Location : Chandigarh
    • Posted On :
    • Posted by : Guley

    Get geo location using jquery and save in a cookie

    var jb_lat = getCookie('jb_lat');
    var jb_lng = getCookie('jb_lng');
    
    if(jb_lat == '' && jb_lng == ''){
        if (navigator.geolocation) {
            navigator.geolocation.getCurrentPosition(showPosition);
        } else { 
            x.innerHTML = "Geolocation is not supported by this browser.";
        }
        function showPosition(location){
            var exdays = 10;
            var d = new Date();
            d.setTime(d.getTime()   (exdays*24*60*60*1000));
            var expires = "expires="  d.toUTCString();
            document.cookie = "jb_lat="   location.coords.latitude   ";"   expires   ";path=/";
            document.cookie = "jb_lng="   location.coords.longitude   ";"   expires   ";path=/";
            window.location.reload();
        }
    
    }
        function getCookie(cname) {
            var name = cname   "=";
            var decodedCookie = decodeURIComponent(document.cookie);
            var ca = decodedCookie.split(';');
            for(var i = 0; i <ca.length; i  ) {
                var c = ca[i];
                while (c.charAt(0) == ' ') {
                    c = c.substring(1);
                }
                if (c.indexOf(name) == 0) {
                    return c.substring(name.length, c.length);
                }
            }
            return "";
        }
  • 3 years-4 months

    Print specific div using jquery

    • Category : jquery
    • Location : Chandigarh
    • Posted On :
    • Posted by : Guley

    You can print specific div or area using this script

    /******Html*********/
     <a href="javascript:void(0);" id="printinvoice"  class="btn btn-warning btn-sm">PRINT INVOICE</a>
    
    <div class="print_div">
                        <div class="col-xs-6 table-responsive">
                            <div class = "sales_header">
                                <span>ORDER NO: # 11380189</span>  
                            </div>
                            <table class="table table-striped table-bordered datatables dataTable">
                                <tbody>
                                    <tr>
                                        <td>Order date</td>
                                        <td>12 Apr 2017 15:55:34</td>
                                    </tr>
                                    <tr>
                                        <td>Order Status</td>
                                        <td> Processed                                    </td>
                                    </tr>
                                    <tr>
                                        <td>Currency</td>
                                        <td>GBP</td>
                                    </tr> 
                                </tbody>
                            </table>
                        </div>  
     </div> 
    /***script**/
    <script src="/assets/js/jQuery.print.js"></script>
    $(document).ready(function() {
        $(document).on('click','#printinvoice',function(){
            //Print ele4 with custom options
            $('.print_div').print({
                //Use Global styles
                globalStyles: true,
                //Add link with attrbute media=print
                mediaPrint: true,
                //Custom stylesheet
                stylesheet: "http://fonts.googleapis.com/css?family=Inconsolata",
                //Print in a hidden iframe
                iframe: true,
                //Don't print this
                noPrintSelector: ""
            });
        });
    });
  • 3 years-4 months

    Prevent requried on ipad and iphone on modal

    • Category : jquery
    • Location : Chandigarh
    • Posted On :
    • Posted by : Guley

    using this code you can prevent required values in html5

    <script src="https://cdnjs.cloudflare.com/ajax/libs/webshim/1.16.0/dev/polyfiller.js" type="text/javascript"></script>
    
    <script> 
            webshim.activeLang('en');
            webshims.polyfill('forms');
            webshims.cfg.no$Switch = true;
    </script>
     
  • 3 years-4 months

    JQuery Ajax form using boostrap validation

    • Category : jquery
    • Location : Chandigarh
    • Posted On :
    • Posted by : Guley

    JQuery Ajax form using boostrap validation

     $(document).on('submit','#formid',function(){
     $(this).formValidation({
                                framework: 'bootstrap',
                                fields: {
                                    name: {
                                        validators: {
                                            notEmpty: {
                                                message: 'The name is required'
                                            }
                                        }
                                    },
                                    email: {
                                        validators: {
                                            notEmpty: {
                                                message: 'The email is required'
                                            }
                                        }
                                    },
                                    password: {
                                        validators: {
                                            notEmpty: {
                                                message: 'The password is required'
                                            }
                                        }
                                    },
                                }
                            })
                            .on('success.form.fv', function(e) {
                                e.preventDefault();
                               var Formdata=$(this).serialize();
                                $.ajax({
                                    type: "POST",
                                    url: '', //add page url here
                                    data: Formdata, //send data from here,
                                    success: function(data) {
                                        alert(data);
                                    }
                                });
                            });
                     });
     
  • 3 years-4 months

    Copy text to clipboard

    • Category : jquery
    • Location : Chandigarh
    • Posted On :
    • Posted by : Guley

    you can copy text to clipboard and paste where you want

    <button class="btn btn-success" id="copyButton" onclick="copyToClipboard('testing')">Copy</button>
    
    <script type="text/javascript">
    function copyToClipboard(elementId) {
    
      // Create a "hidden" input
      var aux = document.createElement("input");
    
      // Assign it the value of the specified element
      aux.setAttribute("value", elementId);
    
      // Append it to the body
      document.body.appendChild(aux);
    
      // Highlight its content
      aux.select();
    
      // Copy the highlighted text
      document.execCommand("copy");
    
      // Remove it from the body
      document.body.removeChild(aux);
    
    }
    </script>
  • 3 years-4 months

    Prevent auto rotation while uploading in php

    • Category : php
    • Location : Chandigarh
    • Posted On :
    • Posted by : Guley

    You can prevent auto image rotation problem using this code

    function correctImageOrientation($filename) {
      if (function_exists('exif_read_data')) {
        $exif = exif_read_data($filename);
        if($exif && isset($exif['Orientation'])) {
          $orientation = $exif['Orientation'];
          if($orientation != 1){
            $img = imagecreatefromjpeg($filename);
            $deg = 0;
            switch ($orientation) {
              case 3:
                $deg = 180;
                break;
              case 6:
                $deg = 270;
                break;
              case 8:
                $deg = 90;
                break;
            }
            if ($deg) {
              $img = imagerotate($img, $deg, 0);        
            }
            // then rewrite the rotated image back to the disk as $filename 
            imagejpeg($img, $filename, 95);
          } // if there is some rotation necessary
        } // if have the exif orientation info
      } // if function exists      
    }
    
    $target_dir = "blog/";
    $target_file = $target_dir . basename($blogimg);
    $imge=correctImageOrientation($target_file);
    move_uploaded_file($_FILES["blogimg"]["tmp_name"], $imge); 
    $query=mysql_query("insert into tablename (`image_name`) values ('$target_file')");
    
  • 3 years-4 months

    Jquery Change css and background

    • Category : jquery
    • Location : Chandigarh
    • Posted On :
    • Posted by : Guley

    You can change background of container using this code

    Html:
    
    <form class="form-inline">
         <div class="form-group">
          <label for="fileToUpload"> <img src="images/upload.png'; ?> " width="200" height="100" id="blah1" /></label>
           <div class="input-group">
      <input type="file" name="exmaple" id="fileToUpload"  required>
      <input type="hidden" id="backupimgurl" val="">
     </div>
      </div>
            <div class="form-group">
        <div class="input-group">
     <select class="form-control" onchange="$('#home-page').css({'background-position':$(this).val()});" name="BackgroundPosition" id="BackgroundPosition">
        <option value="center" selected="selected">Center</option>
        <option value="center top">Center/Top</option>
        <option value="center bottom">Center/Bottom</option>
        <option value="left center">Left/Center</option>
        <option value="left top">Left/Top</option>
        <option value="left bottom">Left/Bottom</option>
        <option value="right center">Right/Center</option>
        <option value="right top">Right/Top</option>
        <option value="right bottom">Right/Bottom</option>
      </select>
     </div>
     </div>
     <div class="form-group">
      <div class="input-group">
      <select class="form-control" onchange="$('#home-page').css({'background-repeat':$(this).val()});" name="BackgroundImageRepeat" id="BackgroundImageRepeat">
       <option value="repeat-x">Repeat Horizontal</option>
       <option value="repeat-y">Repeat Vertical</option>
       <option value="repeat">Repeat</option>
        <option value="no-repeat" selected="selected">No Repeating</option>
          </select>
      </div>
    </div>
    <div class="form-group">
      <div class="input-group">
       <input class="form-control" value="" name="BackgroundColor" style="width:80%; display:inline-block;" maxlength="6" placeholder="color">
     </div>
      </div>
     <div class="form-group">
     <div class="input-group">
         <button type="submit" class="btn btn-success">Save</button>
         </div>
          <div class="input-group">
         <button type="submit" class="btn btn-danger">Cancel</button>
        </div>
       </div>
    </form>
    
    jQuery:
    
    jQuery(document).on('change','#fileToUpload',function(){
     var imgbg = window.URL.createObjectURL(this.files[0]);
      jQuery('#backupimgurl').val(imgbg);
       //console.log(imgbg);
     jQuery('#home-page').css({backgroundImage: "url(" imgbg ")"});
    });
    
  • 3 years-4 months

    Prevent page reload after content changed

    • Category : jquery
    • Location : Chandigarh
    • Posted On :
    • Posted by : Guley

    you can prevent your page if some changes has been done on page.and show warning to user if they won't to leave page

    function enableBeforeUnload() {
        window.onbeforeunload = function (e) {
            return "Discard changes?";
        };
    }
    function disableBeforeUnload() {
        window.onbeforeunload = null;
    }
    $('input, textarea, select').change(function(event){
      enableBeforeUnload();
    });
    /***Using Jquery**/
    $('#formid').submit(function(){
     disableBeforeUnload();
    });
    /***useing html**/
    <form action="" onsubmit="disableBeforeUnload();" method="post>
    //your code
    </form>