In my WordPress v5.7 taxonomy.php
template, I have this below code to get a custom post_type
total posts count. (Code as suggested here at https://stackoverflow.com/a/66751447/3725816).
$term = get_queried_object();
$args = array(
'post_type' => 'your-post-type-name',
'post_status' => 'publish', // get only publish posts
'posts_per_page' => -1, // get all posts
'tax_query' => array(
'relation' => 'AND',
array(
'taxonomy' => 'your-taxonomy-name',
'field' => 'term_id',
'terms' => $term->term_id
)
)
);
$AllPostByTerms = new WP_Query( $args );
echo $AllpostByTerms->post_count;
Now that I have multiple (many) custom post_type’s in my WordPress.
Instead of repeating the same code for each post_type in taxonomy.php
template, is there a way I can get the total posts count of each custom post_type
in a single function / query?
EDIT (Desired result):
I want each custom post_type total posts counts.
Example:
post-type1 = 10,
post-type-name2 = 20,
post-type-name3 = 30
2
Answers
);
You can simply pass a array of all the custom post types in post type parameter
So I just stumbled upon your question and not sure if you’re still interested to see an answer or not, but i’ll add my answer for future reference, just in case somebody needs it.
So, there are multiple ways that you could achieve what you’re looking for! However there are certain things that you didn’t mention in your question!
For example, when counting "total post counts" you didn’t mention which post status you’re referring to!
Another thing that is not clear in your question, is the "type of posts" you’re interested to count!
For example, in addition to your custom-post-type-1, custom-post-type-2, custom-post-type-3, wordpress has its own "built-in" post types such as:
I’ll give you my answer, feel free to customize it as needed!
Since you didn’t mention which specific "post-type" you’re looking for, i’m going to assume you’re interested only in counting your
custom-post-type-1
,custom-post-type-2
andcustom-post-type-3
etc. Therefore, we’re going to use a wordpress function calledget_post_types
in order to dynamically get all of the custom post types we’re interested in. Also, I’m going to assume, you’re interested to countall of the post statuses
. In order to do so, i’ll use a wordpress function calledwp_count_posts
.Now using the above functions, let’s create our magical function that will return
a multidimentional associative array
containing the counts for each status of each custom post type!NO WP_QUERY NEEDED!
This will return a
multidimentional associative array
that looks like this:Now that we have a magical function, all we need to do is to call it and loop through the returned array, like so:
This will return what you’ve asked for!