Ajax Load More Posts in Category Page

I am developing a theme where I need to load more posts with ajax. Currently, when I click load more on the category pages, all the posts are loading. The category.php looks like this : `

>> Design <<

    <?php $counter = 0; ?>
              <?php while ( have_posts() ) : the_post(); ?>
              <?php  $style = ($counter % 2 == 0) ? 'col1 masonry-item ' :  'col2 masonry-item '; ?>
              <article id="post-<?php the_ID(); ?>" class="single-article post <?php echo $style; ?>" >
                  <div class="flip">
                    <a href="<?php the_permalink() ?>" rel="bookmark">
                      <?php if (has_post_thumbnail( $post->ID) ) { ?>
                       <?php if ($counter % 2 == 0) {
                        $image = wp_get_attachment_image_src( get_post_thumbnail_id( $post->ID ), 'masonry_thumb_large');
                       } else {
                        $image = wp_get_attachment_image_src( get_post_thumbnail_id( $post->ID ), 'masonry_thumb_small');
                       } ?>
                      <img src="<?php echo $image[0]; ?>" alt="" />
                      <?php } ?>
                    </a>          
                  </div>
                  <div class="post-meta click">
                    <a href="<?php echo the_permalink() ?>" rel="bookmark">
                      <div class="grid-text">
                        <h2 class="masonry-cat"><?php echo the_category('/ ') ?> | Nº <?php the_field('sub_page_article_number'); ?> </h2>
                        <h2><?php echo get_the_title(); ?></h2>
                              <?php the_excerpt(); ?>
                              <a href="<?php echo the_permalink() ?>" class="click-more">More</a>
                      </div>
                    </a>
                  </div>
              </article>

                  <?php $counter++; endwhile;?>

    </div> <!-- end of postslist -->
    <a class="load_more" data-nonce="<?php echo wp_create_nonce('load_posts') ?>" href="javascript:;"><span>+</span> Load More <span>+</span></a>
</div>`

Once you click the “Load More” button it calls for the /functions.php which has this code :

Read More
add_action( "wp_ajax_load_more", "load_more_func" );
function load_more_func() {
if ( !wp_verify_nonce( $_REQUEST['nonce'], "load_posts" ) ) {
  exit("No naughty business please");
}
$offset = isset($_REQUEST['offset'])?intval($_REQUEST['offset']):0;
$posts_per_page = isset($_REQUEST['posts_per_page'])?intval($_REQUEST['posts_per_page']):10;
$post_type = isset($_REQUEST['post_type'])?$_REQUEST['post_type']:'post';
ob_start(); 


$args = array(
      'post_type'=>$post_type,
    'offset' => $offset,
    'posts_per_page' => $posts_per_page,
    'orderby' => 'date',
    'order' => 'DESC'
      );
$posts_query = new WP_Query( $args );
if ($posts_query->have_posts()) {
  $result['have_posts'] = true; 
  $counter = 0;
  while ( $posts_query->have_posts() ) : $posts_query->the_post(); ?>

  <?php  $style = ($counter % 2 == 0) ? 'col1 masonry-item ' :  'col2 masonry-item '; ?>
  <article id="post-<?php the_ID(); ?>" class="single-article post masonry-brick <?php echo $style; ?>" >
    <div class="flip">
      <a href="<?php the_permalink() ?>" rel="bookmark">
        <?php if (has_post_thumbnail( $post->ID) ) { ?>
          <?php if ($counter % 2 == 0) {
          $image = wp_get_attachment_image_src( get_post_thumbnail_id( $post->ID ), 'masonry_thumb_large');
          } else {
          $image = wp_get_attachment_image_src( get_post_thumbnail_id( $post->ID ), 'masonry_thumb_small');
          } ?>
        <img src="<?php echo $image[0]; ?>" alt="" />
        <?php } ?>
      </a>          
    </div>
    <div class="post-meta click">
      <a href="<?php echo the_permalink() ?>" rel="bookmark">
        <div class="grid-text">
          <h2 class="masonry-cat"><?php echo the_category('/ ') ?> | Nº <?php the_field('sub_page_article_number'); ?> </h2>
          <h2><?php echo get_the_title(); ?></h2>
            <?php the_excerpt(); ?>
            <a href="<?php echo the_permalink() ?>" class="click-more">More</a>
        </div>
      </a>
    </div>
</article>

  <?php $counter++; endwhile;
$result['html'] = ob_get_clean();

else {
$result['have_posts'] = false;


if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
        $result = json_encode($result);
        echo $result; 
    }
else { 
        header("Location: ".$_SERVER["HTTP_REFERER"]);
    }
die();

}

The javascript is :

$('.load_more:not(.loading)').live('click',function(e){
e.preventDefault();
var $load_more_btn = $(this);
var post_type = 'post'; 
var offset = $('#posts_list .single-article').length;
var nonce = $load_more_btn.attr('data-nonce');
$.ajax({
    type : "post",
    context: this,
    dataType : "json",
    url : headJS.ajaxurl,
data : {action: "load_more", offset:offset, nonce:nonce, post_type:post_type, posts_per_page:headJS.posts_per_page},
    beforeSend: function(data) {
        $load_more_btn.addClass('loading').html('+ Loading... +');
        },
        success: function(response) {
                if (response['have_posts'] == 1){
                    var $newElems = $(response['html'].replace(/(rn|n|r)/gm, '')).css({ opacity: 0 });
                    $newElems.imagesLoaded(function(){
                            $newElems.animate({ opacity: 1 });
                            $('#posts_list').append( $newElems ).masonry( 'appended', $newElems); 
                            $load_more_btn.removeClass('loading').html('+ Load More +');
                        });
                    } else {
                        $load_more_btn.removeClass('loading').addClass('end_of_posts').html('<span>End of posts</span>'); 
                    }
                }
    });

I have tried querying the posts differently, but nothing has worked. Any help would be greatly appreciated.

Related posts

1 comment

  1. Your query parameters don’t contain any category arguments. You need to pass and set cat or category_name along with the post type, offset, and posts per page. You can get the current category’s ID via get_queried_object():

    $queried_object = get_queried_object();  
    $cat_id = $queried_object->term_id;
    

    Output and retrieve the value somewhere in your category template, or better, when you enqueue your ajax javascript, check if is_category and use wp_localize_script() to pass that data to your script.

Comments are closed.