Let me explain my need in short:
I want to show post count for any category/any custom taxonomy registered for any custom post type. I searched wordpress forums and in google, found some solutions using
- http://wordpress.org/support/topic/category-post-count-2?replies=6
- http://wordpress.org/support/topic/category-post-count?replies=6
- http://www.intechgrity.com/get-post-count-of-a-category-including-sub-categories-in-wordpress/#
- http://www.web-templates.nu/2008/09/21/get_category_count/index.html
Nothing helped me such way, so I managed my own way with my little knowledge.
wp_get_productcat_postcount($id, $posttype = ‘product’, $taxname = ‘product_cat’)
$id = category or any taxonomy id(term id)
$posttype = post type name, example: post, page, or any custom post type
$taxname = taxonomy name or any category type name, for joomla default taxonomy it will category, post_tag, nav_menu, link_category, post_format, but we can use any custom taxonomy name as I used ‘product_cat’ which is used with custom post type ‘product’ , post type name.
[code lang=”php”]
function wp_get_productcat_postcount($id, $posttype = ‘product’, $taxname = ‘product_cat’) {
$result = wp_cache_get( ‘taxpostcount’.$id, ‘cbtaxpostcount’ );
//var_dump($resul);
if ( false === $result ) {
$args = array(
‘post_type’ => $posttype,
‘post_status’ => ‘publish’,
‘posts_per_page’ => -1,
‘tax_query’ => array(
‘relation’ => ‘AND’,
array(
‘taxonomy’ => $taxname,
‘field’ => ‘id’,
‘terms’ => array( $id )
)
)
);
$query = new WP_Query( $args);
/*
echo ‘<pre>’;
print_r($query->post_count);
echo ‘</pre>’;
*/
$result = (int)$query->post_count;
$cacheresult = wp_cache_set( ‘taxpostcount’.$id, $result, ‘cbtaxpostcount’ );
//var_dump($cacheresult);
}
return $result;
}
[/code]
Note: As I used wordpress object cache for better performance.
Thanks for reading, any comment is appreciable.