0

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.

1 Answer 1

0

You have use ajaxurl when make post request - it's right way but it also mean that now $wp_query, in your my__load__more() function, work with your.site/wp-ajax url instead of your.site/taxonomy. That's why you couldn't get category name from $wp_query->query_vars.

First, I use add_action( 'wp_enqueue_scripts', 'my__enqueue' ); for enqueue your scripts (see example below).

Second, I change arguments you pass to wp_localize_script() function. I offer get name of category when you add script to page instead of get it inside ajax handler:

add_action( 'wp_enqueue_scripts', 'my__enqueue' );
function my__enqueue(){
    wp_enqueue_script( 'my__load__more', get_template_directory_uri() . '/assets/js/load_more.js', array( 'jquery' ), '1.0.0', true );

    global $wp_query;
    $vardi      = $wp_query->query_vars;
    $category   = isset( $vardi[ 'category_name' ] ) ? $vardi[ 'category_name' ] : '';

    $ajaxurl    = admin_url( 'admin-ajax.php' );

    wp_localize_script( 'my__load__more', 'my__params', array(
        'ajaxurl'   => $ajaxurl,
        'category'  => $category,
    ) );
}

Of course, you could add parameter category in same way you add ajaxurl in your code:

wp_localize_script( 'my__load__more', 'my__category', $category );

Pay attention

If you are going to use array in wp_localize_script() function note that now you need use it in your js code as an object element, e.g., my__params.ajaxurl instead of ajaxurl

Third, we need to change your post call:

$.post(my__params.ajaxurl, // if you use array
{
    'action': 'my__load__more',
    'addNum': addNum,
    'getChoose': getChoose,
    'category': my__params.category, // pass category to handler
}

Fourth, and last, change handler:

function my__load__more(){
    // this is your handler beginning

    $args__load = array(
        'posts_per_page' => -1,
        'post_type'      => 'post',
        'post_status'    => 'publish',
    );

    if( !empty( $_POST[ 'category' ] ) ) $args__load[ 'category_name' ] = $_POST[ 'category' ];

    $articles = new WP_Query( $args__load );
    
    // this is your handler ending
}

Value in $_POST[ 'category' ] could be empty, so we no need to use it in our query. Sure, you could add it directly to $args__load array with other parameters without any if, as you want.

Hope it helps ;)

2
  • Thanks so much man! There is only one wrong part in your codes, I fixed it!
    – en0ndev
    Commented Jan 21, 2021 at 15:35
  • @flash, it was pleasure to help!
    – burlakvo
    Commented Jan 21, 2021 at 15:40

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.