Get the current category in a custom function for WP_Query in WordPress

I am adding an ajax load more functionality to my categories in WordPress.

I have created a new file ajax.php and placed a custom function inside with a custom WP_Query. This query retrieves the posts of the next page and so on.

At the moment, when I click the Load More button, it retrieves all posts in all categories but since I’m on the Physics category, I want it to retrieves only the posts of the current category I’m on.

$category = get_query_var('cat'); returns nothing at all string '' (length=0)

ajax.php

add_action('wp_ajax_nopriv_load_more', 'load_more');
add_action('wp_ajax_load_more', 'load_more');

function load_more() {
    $paged = $_POST['page'] + 1;

    $category = get_query_var('cat');

    var_dump($category);

    $query = new WP_Query(array(
        'post_type' => 'post',
        'paged' => $paged
    ));

    if($query->have_posts()) :
        while($query->have_posts()) : $query->the_post();
            get_template_part( 'content', get_post_format() );
        endwhile;
    endif;

    wp_reset_postdata();

    die();
}

Javascript

$('.load-more-button').on('click', function() {
    var that = $(this);
    var page = that.data('page');
    var newPage = page + 1;
    var ajaxurl = that.data('url');

    $.ajax({
        url: ajaxurl,
        type: 'post',
        data: {
            page: page,
            action: 'load_more'
        },
        error: function(response) {
            console.log(response);
        },
        success: function(response) {
            var page = that.data('page', newPage);
            $('.load-more-container').append(response);
        }
    });
});

Read more here: Get the current category in a custom function for WP_Query in WordPress

Leave a Reply

Your email address will not be published. Required fields are marked *