0

Aim

The total to be equal to the amount of post within the selected category or sub category.

What im getting

I am getting 0 when trying to get the number of post available in a category.

My aim is to get the response that shows the total post in that category or sub category selected.

I have tried (code bellow), however I keep getting the response 0 for total

Summery

So I have a custom post type custom_post and I am trying to get the number of post in a selected the category / subcategory selected (using standard category and sub category type taxonomy)

I am using the category / sub-category ID.

Once again, trying to get the response to the the count of post in that category or sub category.

My ajax

<?php // the ajax function
add_action('wp_ajax_filterPosts', 'filterPosts');
add_action('wp_ajax_nopriv_filterPosts', 'filterPosts');

function filterPosts()
{
    $response = [
        'posts' => "",
    ];
    
    $all_args = array(
        'posts_per_page' => -1, // returns all posts
        'post_status' => 'publish',
    );
    
    $filter_args = array(
        'post_status' => 'publish',
    );
    
     if ($_POST['limit']) {
        $filter_args['posts_per_page'] = max (0, (int) $_POST['limit']);
    }
    
    if (isset($_POST['offset'])) {                      
        $filter_args['offset'] = max (0, (int)$_POST['offset']);
    }

     if ($_POST['post_type_js']) {
        $filter_args['post_type'] = $_POST['post_type_js'];
    }

    if ($_POST['category']) {
        $filter_args['cat'] = $_POST['category'];
        
        // Get the total number of posts for the category
        $filter_args['total'] = $_POST['total'];
       
    }

    $filter_query = new WP_Query($filter_args);

    if ($filter_query->have_posts()) :
        while ($filter_query->have_posts()) : $filter_query->the_post();
            $response['posts'] .= load_template_part('/template-parts/posts-filter/single-post');
        endwhile;
        wp_reset_postdata();
    endif;

    echo json_encode($response);
    die();
}

My javascript


Alpine.data("filterPosts", (adminURL) => ({
    posts: "",
    limit: 6,
    total: null,
    category: null,
    post_type_js: post_id,
    showDefault: true,
    showFiltered: false,
    offset: 0,
    
        filterPosts(id) {
        this.showDefault = false;
        this.showFiltered = true;
        this.category = id;
        this.offset = 0; // <-- reset offset to zero
        this.total = 0;
        this.fetchPosts();
    },

Response in console

action: filterPosts
limit: 6
post_type_js: custom_post
offset: 6
category: 1094
total: 0
3
  • 1
    the last code block you shared makes no sense as PHP code, was it written by GPT? Your AJAX code looks incomplete, it's not clear where the admin URL is set, or where your AJAX code is, or how it's called. It's also not clear why you're writing your own AJAX code when WordPress already provides a REST API with this information
    – Tom J Nowell
    Mar 5 at 17:50
  • never tried ChatGDP for code, but maybe it writes cleaner code than me ! lol, understand yoiur point and will update the question
    – Beep
    Mar 5 at 17:56
  • I wrote an answer but after your edit I think there's been a misunderstanding of what you were trying to achieve. Looking at your updated code it's not clear where in your AJAX handler you set the total value, only posts is being set, or where the response in the console is being sent to the console. Is it possible to reproduce this without Alpine data using plain JS that dumps to the console?
    – Tom J Nowell
    Mar 5 at 18:13

1 Answer 1

0

The code in your question uses the old admin AJAX API, and while I would normally advise you switch to the REST API, or fix the AJAX you already have, neither are necessary.

WordPress already provides an endpoint that contains the post count and other information!

https://<yoursite>/wp-json/wp/v2/categories/<category ID>

E.g. on my own site the category with ID 5 can be requested from the REST API at /wp-json/wp/v2/categories/5 and WordPress responds with JSON data:

{"id":5,"count":6,"description":"",...etc

The information includes parent terms, URLs, metadata etc

You can also get a general list of all categories by visiting /wp-json/wp/v2/categories/ without a term ID, and you can also pass additional parameters to filter and constrain the results.

Similar endpoints exist for tags and posts, e.g. /wp/v2/posts

3
  • makes scenes and i should update the ajax, im trying to get the post count for the current category, thats why ive nested it in the category section in my ajax.
    – Beep
    Mar 5 at 18:16
  • 1
    hmm if your goal is just to figure out how many posts are in a category in PHP then that's easy, you don't need the AJAX stuff for that, e.g. $category = get_term_by('name', 'news', 'category'); echo $category->count;
    – Tom J Nowell
    Mar 5 at 18:19
  • thats true, however I need to get it as a response in my javascript.
    – Beep
    Mar 5 at 18:23

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.