Wednesday, 20 July 2016

Pagination using ajax and jquery in wordpress.

Hi Friends,
Today Lets, Learn How to use Pagination using ajax and jquery in wordpress.
Lets start,


Step-1:-  First you have to add following code in your function.php to call ajax in your template.


// Receive the Request post that came from AJAX
add_action( 'wp_ajax_demo-pagination-load-posts', 'cvf_demo_pagination_load_posts' );
// We allow non-logged in users to access our pagination
add_action( 'wp_ajax_nopriv_demo-pagination-load-posts', 'cvf_demo_pagination_load_posts' ); 
function cvf_demo_pagination_load_posts() {
    
    global $wpdb;
    // Set default variables
    $msg = '';
    
    if(isset($_POST['page'])){
        // Sanitize the received page   
        $page = sanitize_text_field($_POST['page']);
        $cur_page = $page;
        $page -= 1;
        // Set the number of results to display
        $per_page = 3;
        $previous_btn = true;
        $next_btn = true;
        $first_btn = true;
        $last_btn = true;
        $start = $page * $per_page;
        
        // Set the table where we will be querying data
        $table_name = $wpdb->prefix . "posts";
        
        // Query the necessary posts
        $all_blog_posts = $wpdb->get_results($wpdb->prepare("
            SELECT * FROM " . $table_name . " WHERE post_type = 'post' AND post_status = 'publish' ORDER BY post_date DESC LIMIT %d, %d", $start, $per_page ) );
        
        // At the same time, count the number of queried posts
        $count = $wpdb->get_var($wpdb->prepare("
            SELECT COUNT(ID) FROM " . $table_name . " WHERE post_type = 'post' AND post_status = 'publish'", array() ) );
        
        
        // Loop into all the posts
        foreach($all_blog_posts as $key => $post): 
            
            // Set the desired output into a variable
            $msg .= '
            <div class = "col-md-12">       
                <h2><a href="' . get_permalink($post->ID) . '">' . $post->post_title . '</a></h2>
                <p>' . $post->post_excerpt . '</p>
<p>' . $post->post_content . '</p>
            </div>';
            
        endforeach;
        
        // Optional, wrap the output into a container
        $msg = "<div class='cvf-universal-content'>" . $msg . "</div><br class = 'clear' />";
        
        // This is where the magic happens
        $no_of_paginations = ceil($count / $per_page);

        if ($cur_page >= 7) {
            $start_loop = $cur_page - 3;
            if ($no_of_paginations > $cur_page + 3)
                $end_loop = $cur_page + 3;
            else if ($cur_page <= $no_of_paginations && $cur_page > $no_of_paginations - 6) {
                $start_loop = $no_of_paginations - 6;
                $end_loop = $no_of_paginations;
            } else {
                $end_loop = $no_of_paginations;
            }
        } else {
            $start_loop = 1;
            if ($no_of_paginations > 7)
                $end_loop = 7;
            else
                $end_loop = $no_of_paginations;
        }
        
        // Pagination Buttons logic     
        $pag_container .= "
        <div class='cvf-universal-pagination'>
            <ul>";

        if ($first_btn && $cur_page > 1) {
            $pag_container .= "<li p='1' class='active'>First</li>";
        } else if ($first_btn) {
            $pag_container .= "<li p='1' class='inactive'>First</li>";
        }

        if ($previous_btn && $cur_page > 1) {
            $pre = $cur_page - 1;
            $pag_container .= "<li p='$pre' class='active'>Previous</li>";
        } else if ($previous_btn) {
            $pag_container .= "<li class='inactive'>Previous</li>";
        }
        for ($i = $start_loop; $i <= $end_loop; $i++) {

            if ($cur_page == $i)
                $pag_container .= "<li p='$i' class = 'selected' >{$i}</li>";
            else
                $pag_container .= "<li p='$i' class='active'>{$i}</li>";
        }
        
        if ($next_btn && $cur_page < $no_of_paginations) {
            $nex = $cur_page + 1;
            $pag_container .= "<li p='$nex' class='active'>Next</li>";
        } else if ($next_btn) {
            $pag_container .= "<li class='inactive'>Next</li>";
        }

        if ($last_btn && $cur_page < $no_of_paginations) {
            $pag_container .= "<li p='$no_of_paginations' class='active'>Last</li>";
        } else if ($last_btn) {
            $pag_container .= "<li p='$no_of_paginations' class='inactive'>Last</li>";
        }

        $pag_container = $pag_container . "
            </ul>
        </div>";
        
        // We echo the final output
        echo 
        '<div class = "cvf-pagination-content">' . $msg . '</div>' . 
        '<div class = "cvf-pagination-nav">' . $pag_container . '</div>';
        
    }
    // Always exit to avoid further execution
    exit();

}


Step-2:-  Now add this following code where you want to display your post.
(like, index.php,home.php,etc...)


<div class="col-md-12 content">
        <div class = "inner-box content no-right-margin darkviolet">
            <script type="text/javascript">
            jQuery(document).ready(function($) {
                // This is required for AJAX to work on our page
                var ajaxurl = '<?php echo admin_url('admin-ajax.php'); ?>';
                
                function cvf_load_all_posts(page){
                    // Start the transition
                    $(".cvf_pag_loading").fadeIn().css('background','#ccc');
                    
                    // Data to receive from our server
                    // the value in 'action' is the key that will be identified by the 'wp_ajax_' hook 
                    var data = {
                        page: page,
                        action: "demo-pagination-load-posts"
                    };
                    
                    // Send the data
                    $.post(ajaxurl, data, function(response) {
                        // If successful Append the data into our html container
                        $(".cvf_universal_container").append(response);
                        // End the transition
                        $(".cvf_pag_loading").css({'background':'none', 'transition':'all 1s ease-out'});
                    });
                }
                
                // Load page 1 as the default
                cvf_load_all_posts(1);
                
                // Handle the clicks
                $('.cvf_universal_container .cvf-universal-pagination li.active').live('click',function(){
                    var page = $(this).attr('p');
                    cvf_load_all_posts(page);
                    
                });
                            
            }); 
            </script>
            <div class = "cvf_pag_loading">
                <div class = "cvf_universal_container">
                    <div class="cvf-universal-content"></div>
                </div>
            </div>
            
        </div>      
    </div>


Step-3:- To see your Output in good way put this following code in your style.css


.cvf_pag_loading {padding: 20px;}
.cvf-universal-pagination ul {margin: 0; padding: 0;}
.cvf-universal-pagination ul li {display: inline; margin: 3px; padding: 4px 8px; background: #FFF; color: black; }
.cvf-universal-pagination ul li.active:hover {cursor: pointer; background: #1E8CBE; color: white; }
.cvf-universal-pagination ul li.inactive {background: #7E7E7E;}
.cvf-universal-pagination ul li.selected {background: #1E8CBE; color: white;}


End of this adding file you will see like this in your page. 



Friday, 8 July 2016

Dynamic Dependent Select Box using Ajax in WordPress

Today  i will explain how to create a dynamic dependent select box which fetches records from database without reload the page,  this can be achieved using jQuery and Ajax, using Ajax in WordPress. We can submit and receive data using jQuery, and Ajax will handle server side request.

Let's Start....

1. Create two tables of country and city:-

    CREATE TABLE IF NOT EXISTS `country` ( `country_id` int(11) NOT NULL AUTO_INCREMENT, `country_name`  

varchar(50) NOT NULL, PRIMARY KEY (`country_id`) );

CREATE TABLE IF NOT EXISTS `city` ( `city_id` int(11) NOT NULL AUTO_INCREMENT, `city_name` varchar(50)

  NOT NULL, `country_id` int(11) NOT NULL, PRIMARY KEY (`city_id`) ); 

 

2. Create a plugin to use Ajax in WordPress:-

  Create a new folder in wp-content/plugins/  Name of ajax-cities. just remember that plugin folder and file name will be same, i used ajax-cities/ folder name and ajax-cities.php file name in this folder. And activate the plugin.

 

 

3. Create main plugin file name ajax-cities.php:

 

Make ajax-cities folder in wordpress\wp-content\plugins\ajax-cities   and make one php file in same folder name of ajax-cities.php and put this following code  

ajax-cities.php 

<?php
/**
 * Plugin Name: Ajax Cities
 * Description: Allows to select cities according to the country
 * Version: 1.0.0
 * Author: Jayesh Borase
 * License: GPL2
 */

add_action( 'wp_enqueue_scripts', 'my_enqueue' );
function my_enqueue() {
    wp_enqueue_script( 'ajax-script', plugins_url( '/cities.js', __FILE__ ), array('jquery'));
    wp_localize_script( 'ajax-script', 'ajax_object', array( 'ajax_url' => admin_url( 'admin-ajax.php' )));
}

function my_action() {
$country_id = $_REQUEST['id'];
global $wpdb;
$cities = $wpdb->get_results($wpdb->prepare("SELECT * FROM city WHERE country_id='".$country_id."'",13,'gargle'),ARRAY_A);
foreach($cities as $city)
{ ?>
<option value="<?php echo $city["city_id"]; ?>"><?php echo $city["city_name"]; ?></option>
<?php }
die();
}
add_action('wp_ajax_my_action', 'my_action' );
add_action('wp_ajax_nopriv_my_action', 'my_action');
?>

 

4. Create Ajax file to handle request with name cities.js

 Make One .js file in same folder name of cities.js and past following code.

(function($) {
$(document).ready(function(){
    $('.country').change(function(){  
    var country_id = $(this).val();
    $.ajax({
            cache: false,
            type: "POST",
            url: ajax_object.ajax_url,
            data: {
                action : 'my_action',
                id : country_id,
                   },
            success: function(citydata)
                {
                jQuery('.city').html(citydata);
                }
            });
    });
});
})(jQuery);

 

  Note: These are the two files which are placed in our ajax-cities plugin.

 

5. Publish a template page with HTML form of country and    city select drop down list

Create a page in your theme folder with name page-select-country.php and paste the below code.using this below code in your dashboard you can see in Template the same option of theme name.

<?php

/**
 * Template Name: dropdown
 *
 * @package WordPress
 * @subpackage Twenty_Fourteen
 * @since Twenty Fourteen 1.0
 */

get_header(); ?>
<div id="contents">
<h1>Select Country</h1><br/><br/>
<form name="form" method="post" action="">
<label>Country: </label><select name="country" class="country">
<option>Select Country</option>
<?php
global $wpdb;
$countries = $wpdb->get_results($wpdb->prepare("SELECT * FROM country",13,'gargle'),ARRAY_A);
foreach($countries as $country)
{ ?>          
<option value="<?php echo $country["country_id"]; ?>"><?php echo $country["country_name"]; ?></option>
<?php } ?>
</select>
<label>City: </label><select name="city" class="city">
<option>Select City</option>
</select>
</form>
</div>
<?php get_footer(); ?>


 
 

Select your Template and publish the page.

  Final Output:-