Skip to content

Instantly share code, notes, and snippets.

@Pamps
Last active January 25, 2023 13:48
Show Gist options
  • Save Pamps/25d7615e2c5c059500af9d4512489c96 to your computer and use it in GitHub Desktop.
Save Pamps/25d7615e2c5c059500af9d4512489c96 to your computer and use it in GitHub Desktop.
WordPress: How to get the post count for a term and post type. Found out more at https://www.darrenlambert.com/wordpress-how-to-get-the-post-count-for-a-term-and-post-type/
/**
* Returns the number of posts for a term in a taxonomy, for a post type
* Found out more at https://www.darrenlambert.com/wordpress-how-to-get-the-post-count-for-a-term-and-post-type/
* @param string $post_type
* @param string $taxonomy
* @return int count
*/
function get_post_count_for_term_and_post_type( $term_id, $taxonomy, $post_type ) {
// Build the args
$args = array(
'post_type' => $post_type,
'posts_per_page' => -1,
'tax_query' => array(
array(
'taxonomy' => $taxonomy,
'field' => 'id',
'terms' => $term_id,
)
)
);
// Get the posts
$posts = get_posts( $args );
// Return the count
return count($posts);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment