Friday 14 April 2023

how to implement a "Show More" and "Show Less" button that displays posts using AJAX in WordPress

Here's an example code that shows how to implement a "Show More" and "Show Less" button that displays posts using AJAX in WordPress. This code will display 10 posts by default and then display a "Show More" button to display the next 10 posts. Once all posts are displayed, the "Show More" button will be hidden and a "Show Less" button will be displayed instead. The "Show Less" button will then remove the last 2 posts until only the first 10 remain. 


function load_more_scripts() {
2    wp_enqueue_script( 'loadmore', get_template_directory_uri() . '/js/loadmore.js', array('jquery') );
3    wp_localize_script( 'loadmore', 'loadmore_params', array(
4        'ajax_url' => admin_url( 'admin-ajax.php' ),
5        'posts' => json_encode( $wp_query->query_vars ),
6        'current_page' => get_query_var( 'paged' ) ? get_query_var('paged') : 1,
7        'max_page' => $wp_query->max_num_pages
8    ) );
9}
10add_action( 'wp_enqueue_scripts', 'load_more_scripts' );
1112function loadmore_ajax_handler(){
13    $args = json_decode( stripslashes( $_POST['query'] ), true );
14    $args['paged'] = $_POST['page'] + 1; 
15    $args['post_status'] = 'publish';
1617    query_posts( $args );
1819    if( have_posts() ) :
2021        while( have_posts() ): the_post();
2223            // Display your post content here
2425        endwhile;
2627    endif;
2829    die;
30}
31add_action('wp_ajax_loadmore', 'loadmore_ajax_handler');
32add_action('wp_ajax_nopriv_loadmore', 'loadmore_ajax_handler');
3334function custom_load_more_button() {
3536    global $wp_query;
3738    $total_pages = $wp_query->max_num_pages;
3940    if ($total_pages > 1){
4142        $current_page = max(1, get_query_var('paged'));
4344        echo '<div id="load-more" class="load-more-container text-center"><button class="btn btn-primary" data-page="' . $current_page . '" data-url="' . admin_url('admin-ajax.php') . '">Show More</button></div>';
45        echo '<div id="show-less" class="load-more-container text-center" style="display:none;"><button class="btn btn-primary" data-page="' . $current_page . '" data-url="' . admin_url('admin-ajax.php') . '">Show Less</button></div>';
4647    }
4849}
50add_action( 'woocommerce_after_shop_loop', 'custom_load_more_button', 10 );
And here's the JS code that goes along with it:
1jQuery(function($){
2    $('#load-more button').click(function(){
34        var button = $(this),
5            data = {
6            'action': 'loadmore',
7            'query': loadmore_params.posts,
8            'page' : loadmore_params.current_page
9        };
1011        $.ajax({
12            url : loadmore_params.ajax_url,
13            data : data,
14            type : 'POST',
15            beforeSend : function ( xhr ) {
16                button.text('Loading...'); // Change the button text to "Loading..."
17            },
18            success : function( data ){
19                if( data ) {
20                    button.text( 'Show More' ).prev().before(data); // Insert new posts
21                    loadmore_params.current_page++;
2223                    if ( loadmore_params.current_page == loadmore_params.max_page ) {
24                        $('#load-more').hide(); // If last page, hide the button
25                        $('#show-less').show(); // Show "Show Less" button
26                    }
27                } else {
28                    $('#load-more').hide(); // If no data, hide the button
29                }
30            }
31        });
32    });
3334    $('#show-less button').click(function(){
3536        var button = $(this),
37            data = {
38            'action': 'loadmore',
39            'query': loadmore_params.posts,
40            'page' : loadmore_params.current_page - 2
41        };
4243        $.ajax({
44            url : loadmore_params.ajax_url,
45            data : data,
46            type : 'POST',
47            beforeSend : function ( xhr ) {
48                button.text('Loading...'); // Change the button text to "Loading..."
49            },
50            success : function( data ){
51                if( data ) {
52                    button.text( 'Show Less' ).prev().before(data); // Remove posts
53                    loadmore_params.current_page--;
5455                    if ( loadmore_params.current_page == 1 ) {
56                        $('#show-less').hide(); // If first page, hide the button
57                        $('#load-more').show(); // Show "Show More" button
58                    }
59                } else {
60                    $('#show-less').hide(); // If no data,

Popular Post