Aleš Sýkora / December 6, 2023 / 0 comments
Custom Post Type Taxonomy Post Count Using the Toolset Plugin
min read / WordPress / Share on: Twitter, LinkedIn, Facebook
Post summary: Add this snippet to your functions.php or create your own plugin…
If you’re using the Toolset plugin on your WordPress site and you need a way to display the count of posts in a specific taxonomy for a custom post type, this guide will help you achieve just that. By adding a small piece of code to your site, you can easily display this count anywhere you need.
Step 1: Adding the Code Snippet
First, you need to add a custom function to your website. You can do this by inserting the following code into your theme’s functions.php
file or by creating a small custom plugin or use code snipppets plugin.
function my_taxonomy_posts_count_func( $atts ) {
extract(shortcode_atts(array(
'post_type' => 'post',
), $atts));
global $WP_Views;
$term = $WP_Views->get_current_taxonomy_term();
$args = array(
'post_type' => $post_type,
'tax_query' => array(
array(
'taxonomy' => $term->taxonomy,
'field' => 'id',
'terms' => $term->term_id,
)
),
'order' => 'ASC',
'posts_per_page' => -1,
'suppress_filters' => 0,
);
$posts = get_posts($args);
return ($posts) ? count($posts) : 0;
}
add_shortcode('my-taxonomy-posts-count', 'my_taxonomy_posts_count_func');
This function creates a shortcode that, when used, will count the number of posts within a specific taxonomy for a given custom post type.
Step 2: Using the Shortcode in Your View
Once you have the code in place, you can use the shortcode [my-taxonomy-posts-count post_type="your_custom_post_type_slug"]
in your view. Replace "your_custom_post_type_slug"
with the slug of your custom post type. For example, if your custom post type is “jobs,” the shortcode would look like this:
[my-taxonomy-posts-count post_type="jobs"]
This shortcode will dynamically count and display the number of ‘jobs’ posts within the current taxonomy term.
Conclusion
By following these steps, you can add a dynamic post count for any custom post type and taxonomy combination on your WordPress site. This is particularly useful for sites with a large number of custom post types and taxonomies, allowing for a more interactive and informative user experience.
Fuel my passion for writing with a beer🍺
Your support not only makes me drunk but also greatly motivates me to continue creating content that helps. Cheers to more discoveries and shared success. 🍻