1

Hello I have set up custom Ajax load more without plugins, but it’s only showing 3 posts on home page, and when clicking on button to load more it’s not loading anything. As I am a beginner I am pretty sure I have done a few coding mistakes. I believe I might have done the mistake in index.php

Here are the codes I used:

First I have added this to functions.php

function bsubash_load_more_scripts() {
    wp_enqueue_script('jquery');
    wp_register_script( 'loadmore_script', get_stylesheet_directory_uri() . '/js/ajax.js', array('jquery') );
    wp_localize_script( 'loadmore_script', 'loadmore_params', array(
        'ajaxurl' => admin_url('admin-ajax.php'),
    ) );

    wp_enqueue_script( 'loadmore_script' );
}
 
add_action( 'wp_enqueue_scripts','bsubash_load_more_scripts' );

Then under the same line I’ve added this

function bsubash_loadmore_ajax_handler(){
    $type = $_POST['type'];
    $category = isset($_POST['category']) ? $_POST['category']: '';
    $args['paged'] = $_POST['page'] + 1;
    $args['post_status'] = 'publish';
    $args['posts_per_page'] =  $_POST['limit'];
    if($type == 'archive'){
        $args['category_name'] = $category;
    }
    query_posts( $args );
    if( have_posts() ) :
        while(have_posts()): the_post();    
//write your single post card   
            the_title();
the_excerpt();
    endwhile;
    endif;
    die;
}
add_action('wp_ajax_loadmore','bsubash_loadmore_ajax_handler');
add_action('wp_ajax_nopriv_loadmore','bsubash_loadmore_ajax_handler');

After that, in my index.php where I added this code to the code that I use to display my posts on homepage

<div class="container"> <!-- container start -->
    <div class="row overflow-hidden"> <!-- row start -->
    <?php
      $paged = ( get_query_var('page') ) ? get_query_var('page') : 1;
      $latests = new WP_Query(array(
        'post_type' => 'post',
        'posts_per_page' => 3,
        'paged' => $paged
      ));
      
      while($latests->have_posts()): $latests->the_post();
            ?>
            <div class="col-xs-6 col-sm-6 col-md-6 col-lg-4 col-xl-3"> <!-- columns start -->
                <a href="<?php the_permalink(); ?>">
                    <div class="title-box mx-auto mb-0">
                        <h1 class="title-color">
                            <?php
                                $the_title = get_the_title();
                            if ( $the_title ) {
                                echo esc_html( the_title() );
                            } else {
                                echo 'No Title';
                            }
                            ?>
                        </h1>
                        <?php
                        if ( has_post_thumbnail() ) {
                            the_post_thumbnail('homepage-thumbnail', array('class' => 'featured-image'));
                        } else {
                            ?>
                                <img class="img-fluid" src="<?php echo esc_url_raw( get_template_directory_uri() . '/images/bg.jpg' ); ?>">
                                <?php
                        }
                        ?>
                    </div>
                </a>
            </div>
            <?php
        endwhile; // End of the loop.
        ?>
    </div>
</div> <!-- container ends -->

<script>
   var limit = 5,
       page = 1,
       type = 'latest',
       category = '',
       max_pages_latest = <?php echo $latests->max_num_pages ?>
</script>
<?php if ( $latests->max_num_pages > 1 ){
   echo '<div class="load_more text-center">
                    <a href="#" class="btn btn-circle btn-inverse btn-load-more">More Article</a> 
                </div>';
        }else{?>
<article>
   <h1>Sorry...</h1>
   <p><?php _e('Sorry, No Posts Available !'); ?></p>
</article>
<?php }
   wp_reset_query();
   ?>


and finally I added js files to /js/ajax.php

jQuery(function($) {
    $('.btn-load-more').click(function(e) {
        e.preventDefault();
        var button = $(this),
            data = {
                'action': 'loadmore',
                'limit': limit,
                'page': page,
                'type': type,
                'category': category
            };

        $.ajax({
            url: loadmore_params.ajaxurl,
            data: data,
            type: 'POST',
            beforeSend: function(xhr) {
                button.text('Loading...'); // change the button text, you can also add a preloader image
            },
            success: function(data) {
                if (data) {
$(".latest_posts_wrapper").append(data);
                    page++;
                    button.text('More Articles');
                    if (page == max_pages_latest)
                        button.remove(); // if last page, remove the button
                } else {
                    button.remove(); // if no data, remove the button as well
                }
            }
        });
    });

});
5
  • Have you done any debugging? Is your JS script being loaded? Is the request being sent? Can you narrow down when the failure is occurring? Commented Jan 17, 2023 at 14:06
  • @JacobPeattie JavaScript is being loaded, I believe I made the mistake in index.php while adding the loop Commented Jan 17, 2023 at 14:22
  • Well your code is outputting into .latest_posts_wrapper, but that doesn't exist in index.php, as far as I can tell. Commented Jan 17, 2023 at 14:24
  • You could try changing the $in_footer parameter of wp_register_script to true. I it looks like your jQuery would load before the <script> tags in your markup, although I don't know enough about Javascript to know if that would work either. It seems like variable scope would still be an issue.
    – Shoelaced
    Commented Jan 17, 2023 at 14:31
  • I have lack knowledge of javascript too, and I have tried adding the correct class but still didn't work Commented Jan 17, 2023 at 15:59

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.