admin管理员组

文章数量:1124379

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

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
Share Improve this question edited Mar 5, 2024 at 18:00 Beep asked Mar 5, 2024 at 17:29 BeepBeep 297 bronze badges 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 Commented Mar 5, 2024 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 Commented Mar 5, 2024 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 Commented Mar 5, 2024 at 18:13
Add a comment  | 

1 Answer 1

Reset to default 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

本文标签: custom taxonomyget total post in category via ajx