Skip to content

Instantly share code, notes, and snippets.

@codersantosh
Created May 17, 2021 09:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save codersantosh/5a9d72abc002db2aa3d9b24ed5a6ab09 to your computer and use it in GitHub Desktop.
Save codersantosh/5a9d72abc002db2aa3d9b24ed5a6ab09 to your computer and use it in GitHub Desktop.
/**
* Get Post/Post Type Count in the given Taxonomy
*
* @param $post_type string any post type
* @param $taxonomy string any taxonomy
* @param $is_exists string NOT EXISTS or EXISTS
*
* @return String Number of Post count
*/
function prefix_get_post_count_in_taxonomy($post_type, $taxonomy, $is_exists = 'NOT EXISTS')
{
global $wpdb;
$count = $wpdb->get_var(
"
select COUNT(*) as post_count
FROM $wpdb->posts as A
WHERE $is_exists (
SELECT 1
FROM
$wpdb->term_relationships as B
INNER JOIN $wpdb->term_taxonomy as C
ON C.term_taxonomy_id = B.term_taxonomy_id
WHERE C.taxonomy = '$taxonomy'
AND B.object_id = A.ID
)
AND A.post_type = '$post_type'
"
);
return $count;
}
/**
* Example
*
* Post type: download
* Taxonomy: download_category
* Is Exist: EXISTS
*/
echo prefix_get_post_count_in_taxonomy('download', 'download_category', 'EXISTS');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment