Skip to content

Instantly share code, notes, and snippets.

@adamdehaven
Last active February 8, 2018 14:37
Show Gist options
  • Save adamdehaven/2d6be76f11cf1bdb01b61f0ce4f80177 to your computer and use it in GitHub Desktop.
Save adamdehaven/2d6be76f11cf1bdb01b61f0ce4f80177 to your computer and use it in GitHub Desktop.
Function to get the post count from a given category or taxonomy term or terms, including their children in WordPress.
<?php
/*
* Function to get the post count from a given category or taxonomy
* term or terms, including their children.
*
* @param (int|array|string) $term Single integer value, or array of integers or "all"
* @param (string) $taxonomy
* @param (array) $args Array of arguments to pass to WP_Query
* @return $q->found_posts
*
*/
function ad_get_term_post_count( $term = '', $taxonomy = 'category', $args = [] )
{
// Lets first validate and sanitize our parameters, on failure, just return false
if ( !$term ) {
return false;
}
if ( $term !== 'all' ) {
if ( !is_array($term) ) {
$term = filter_var( $term, FILTER_VALIDATE_INT );
} else {
$term = filter_var_array( $term, FILTER_VALIDATE_INT );
}
}
if ( $taxonomy !== 'category' ) {
$taxonomy = filter_var( $taxonomy, FILTER_SANITIZE_STRING );
if ( !taxonomy_exists( $taxonomy ) ) {
return false;
}
}
if ( $args ) {
if ( !is_array ) {
return false;
}
}
// Set our default args
$defaults = [
'post_status' => 'publish',
'posts_per_page' => 1, // don't need more than 1 to run query
'fields' => 'ids'
];
if ( $term !== 'all' ) {
$defaults['tax_query'] = [
[
'taxonomy' => $taxonomy,
'terms' => $term
]
];
}
$combined_args = wp_parse_args( $args, $defaults );
$q = new WP_Query( $combined_args );
// Return the post count
return $q->found_posts;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment