I have a load more script in WordPress, everything is perfect on the homepage but there is a problem in the taxonomy page. So when you click on the category page, it pulls out all the articles. When you manually enter the category name in $args__load['category_name']
below, everything is fine. But when you call the category of the current page with $wp_query
, it extracts all articles.
PHP
<?php
wp_enqueue_script('my__load__more', get_template_directory_uri() . '/assets/js/load_more.js', array('jquery'), '1.0.0', true);
wp_localize_script('my__load__more', 'ajaxurl', admin_url('admin-ajax.php'));
function my__load__more() {
$count = get_option('posts_per_page');
$add = $_POST['addNum'];
$getChoose = $_POST['getChoose'];
$count = $count + $add;
$read = 1;
$args__load = array(
'posts_per_page' => -1,
'post_type' => 'post',
'post_status' => 'publish',
);
global $wp_query;
$vardi = $wp_query->query_vars;
$args__load['category_name'] = $vardi['category_name'];
$articles = new WP_Query( $args__load );
$getPosts = array();
if( $articles->have_posts() ) {
while( $articles->have_posts() ) {
$articles->the_post();
if($read > $count && $read <= $count+$getChoose) {
ob_start(); // start the buffer to capture the output of the template
get_template_part('contents/content_general');
$getPosts[] = ob_get_contents(); // pass the output to variable
ob_end_clean(); // clear the buffer
if( $read == $articles->found_posts )
$getPosts[] = false;
}
$read++;
}
}
echo json_encode($getPosts);
die();
}
add_action( 'wp_ajax_my__load__more', 'my__load__more' );
add_action( 'wp_ajax_nopriv_my__load__more', 'my__load__more' );
?>
JS
(function($){
"use strict";
var addNum = 0;
var getChoose = 5;
var clicked = false;
var readyCount = false;
$(".load__more__button").click(function() {
if (!clicked) {
$('.load__more__button').text('Loading...');
if (readyCount == true) {
addNum = addNum + getChoose;
}
readyCount = true;
$.post(ajaxurl,
{
'action': 'my__load__more',
'addNum': addNum,
'getChoose': getChoose,
},
function(response) {
var posts = JSON.parse(response);
for( var i = 0; i < posts.length; i++ ) {
if( posts[i] == false )
$(".load__more__button").fadeOut();
else
$('.the__content.last').removeClass('last');
$(posts[i]).appendTo(".content__area").hide().fadeIn("slow");
$('.content__area').children().last().addClass('last');
$('.load__more__button').text('Load More');
}
});
$(document).ajaxStop(function () {
clicked = false;
});
clicked = true;
}
});
}(jQuery));
But replacing this part with an existing category name, it works.
global $wp_query;
$vardi = $wp_query->query_vars;
$args__load['category_name'] = "business"; // $vardi['category_name'];
I guess it doesn't see wp_query. Thank you in advance for the help.