Using Ajax and WP_Query to load more posts on category page fails

I’m using the code below to load more articles on click beneath the 10 posts that are already loaded on page load.
It works perfectly on my front page, but when I use it on my category page, it will show all posts instead of just the ones within the category.
For example: "domain/category/testcategory/"
I tried adding this to the functions.php part where $args is specified:

        'category'          => get_queried_object_id(),
        'category__in'      => array( get_queried_object_id() ),

No luck though. It actually broke the whole thing when I added it. It stopped loading more posts on click.
Can someone tell me what I’m missing? I just started learning WP_Query and Ajax and I’ve been trying to get this sorted for a couple of days now. Any advice would be appreciated.
This is the entire code I’m using:

// functions.php

function mytheme_scripts() {
 wp_register_script( 'core-js', get_template_directory_uri() .'/loadmore.js', array('jquery'), '', true );
 wp_enqueue_script( 'core-js' );
wp_localize_script( 'core-js', 'ajax_posts', array(
    'ajaxurl' => admin_url( 'admin-ajax.php' ),
    'noposts' => __('No older posts found', 'ths-theme'),
)); 
}
add_action( 'wp_enqueue_scripts', 'mytheme_scripts' );

function more_post_ajax(){

    $ppp = (isset($_POST["ppp"])) ? $_POST["ppp"] : 3;
    $page = (isset($_POST['pageNumber'])) ? $_POST['pageNumber'] : 0;



    header("Content-Type: text/html");

    $queried_object = get_queried_object_id();  
    $cat_id = $queried_object->term_id;
    $args = array(      
        'offset' => '1',
        'suppress_filters' => true,
        'post_type' => 'post',
        'posts_per_page' => $ppp,
        'paged'    => $page,
        'category'      => array( get_queried_object_id() ),

    );


    if ( isset( $args['offset'] ) ) {
        $offset = absint( $args['offset'] );
        $args['offset'] = absint( ( $args['paged'] - 1 ) * $args['posts_per_page'] ) + $offset;
    }

    $category = get_the_category();
    $parent = get_cat_name( $category[1]->parent );
    $child = get_cat_name($category);
    $parentlink = get_category_link( $category[1]->parent );

    $loop = new WP_Query($args);

    $out = '';

    if ($loop -> have_posts()) :  while ($loop -> have_posts()) : $loop -> the_post();
    $category = get_the_category();
    $parent = get_cat_name( $category[1]->parent );
    $child = get_cat_name($category);
    $parentlink = get_category_link( $category[1]->parent );
        $out .= ' <div class="masonry-item"><div class="masonry-content"><div class="i-container">
        <a href=" '.get_the_permalink().' ">'.get_the_post_thumbnail( get_the_ID(), $size = 'latest-front' , $attr ).'</a>

                <div class="featured-cat f-c-latest"><a href=" ' . $parentlink .' ">
                '.$parent.'
                </a></div></div>
                <a href=" '.get_the_permalink().' ">
                <h2>'.get_the_title().'</h2></a>
                
                <div class="latestda">
                <span class="date">'.get_the_date( 'dS M Y' ).' </span>
                <span class="bold">COMMENTS '.get_comments_number().'</span></div>
         </div></div> ';

    endwhile;
    endif;
    wp_reset_postdata();
    die($out);
}

add_action('wp_ajax_nopriv_more_post_ajax', 'more_post_ajax');
add_action('wp_ajax_more_post_ajax', 'more_post_ajax');
 ?>
//category.php

                    <div class="latest-block">
                <header class="archive-header">
                <h1 class="archive-title"><?php single_cat_title( '', true ); ?></h1>
                </header>
                    <div  id="ajax-posts" class="masonry">
                        <?php
                            $postsPerPage = 10;
                            $args = array(
                            'category'          => get_queried_object_id(),
                            'category__in'      => array( get_queried_object_id() ),
                            'post_type' => 'post',
                            'posts_per_page' => $postsPerPage,
                            );
                        $loop = new WP_Query($args);
                        while ($loop->have_posts()) : $loop->the_post();
                        ?>
 

                        <div class="masonry-item">
                            <div class="masonry-content">
                                <div class="i-container">
                                    <a href="<?php the_permalink(); ?>" title="<?php the_title_attribute(); ?>">
                                    <?php the_post_thumbnail( 'latest-front' );?>
                                    </a>
                                    <?php    $category = get_the_category();
                                    $parent = get_cat_name( $category[1]->parent );
                                    $child = get_cat_name($category);
                                    $parentlink = get_category_link( $category[1]->parent );
                                    if ( ! empty( $parent ) ) {
                                    echo '<div class="featured-cat f-c-latest"><a href=" ' . $parentlink .' ">';
                                    echo $parent;
                                    echo '</a></div>';
                                    }
                                    else {
                                    echo $child; 
                                    }
                                    ?>
                                </div>
                                <a href="<?php the_permalink(); ?>" title="<?php the_title_attribute(); ?>">
                                <h2><?php the_title(); ?></h2>
                                </a>
                                <?php
                                $articleda = get_the_date( 'dS M Y' );
                                echo '<div class="latestda">';
                                echo '<span class="date">';
                                echo $articleda;
                                echo '</span>';
                                echo ' <span class="bold">COMMENTS ';
                                echo get_comments_number();
                                echo '</span></div>';
                                ?> 
                              
                            </div>
                        </div>  <?php
                                    endwhile;
                                    wp_reset_postdata();
                                ?>
                    </div>
                    <div id="more_posts" class="misha_loadmore">Load More</div>
// loadmore.js

var ppp = 10; // Post per page
var pageNumber = 1;


function load_posts(){
    pageNumber++;
    var str = '&pageNumber=' + pageNumber + '&ppp=' + ppp + '&action=more_post_ajax';
    jQuery.ajax({
        type: "POST",
        dataType: "html",
        url: ajax_posts.ajaxurl,
        data: str,
        success: function(data){
            var jQuerydata = jQuery(data);
            if(jQuerydata.length){
                jQuery("#ajax-posts").append(jQuerydata);
                jQuery("#more_posts").attr("disabled",false);
            } else{
                jQuery("#more_posts").attr("disabled",true);
            }
        },
        error : function(jqXHR, textStatus, errorThrown) {
            jQueryloader.html(jqXHR + " :: " + textStatus + " :: " + errorThrown);
        }

    });
    return false;
}

jQuery("#more_posts").on("click",function(){ // When btn is pressed.
    jQuery("#more_posts").attr("disabled",true); // Disable the button, temp.
    load_posts();
    jQuery(this).insertAfter('#ajax-posts'); // Move the 'Load More' button to the end of the the newly added posts.
});

$299 Affordable Web Design WordPress

This article was republished from its original source.
Call Us: 1(800)730-2416

Pixeldust is a 20-year-old web development agency specializing in Drupal and WordPress and working with clients all over the country. With our best in class capabilities, we work with small businesses and fortune 500 companies alike. Give us a call at 1(800)730-2416 and let’s talk about your project.

FREE Drupal SEO Audit

Test your site below to see which issues need to be fixed. We will fix them and optimize your Drupal site 100% for Google and Bing. (Allow 30-60 seconds to gather data.)

Powered by

Using Ajax and WP_Query to load more posts on category page fails

On-Site Drupal SEO Master Setup

We make sure your site is 100% optimized (and stays that way) for the best SEO results.

With Pixeldust On-site (or On-page) SEO we make changes to your site’s structure and performance to make it easier for search engines to see and understand your site’s content. Search engines use algorithms to rank sites by degrees of relevance. Our on-site optimization ensures your site is configured to provide information in a way that meets Google and Bing standards for optimal indexing.

This service includes:

  • Pathauto install and configuration for SEO-friendly URLs.
  • Meta Tags install and configuration with dynamic tokens for meta titles and descriptions for all content types.
  • Install and fix all issues on the SEO checklist module.
  • Install and configure XML sitemap module and submit sitemaps.
  • Install and configure Google Analytics Module.
  • Install and configure Yoast.
  • Install and configure the Advanced Aggregation module to improve performance by minifying and merging CSS and JS.
  • Install and configure Schema.org Metatag.
  • Configure robots.txt.
  • Google Search Console setup snd configuration.
  • Find & Fix H1 tags.
  • Find and fix duplicate/missing meta descriptions.
  • Find and fix duplicate title tags.
  • Improve title, meta tags, and site descriptions.
  • Optimize images for better search engine optimization. Automate where possible.
  • Find and fix the missing alt and title tag for all images. Automate where possible.
  • The project takes 1 week to complete.