Skip to content

Instantly share code, notes, and snippets.

@verteb
Created June 26, 2013 13:56
Show Gist options
  • Save verteb/5867549 to your computer and use it in GitHub Desktop.
Save verteb/5867549 to your computer and use it in GitHub Desktop.
Wordpress: Count posts by term
function fc_count_posts_with_term($term_slug, $taxonomy)
{
global $wpdb;
$term = get_term_by( 'slug', $term_slug, $taxonomy );
$st = $wpdb->prepare("SELECT COUNT(*) FROM $wpdb->posts p
INNER JOIN $wpdb->term_relationships tr
ON (p.ID = tr.object_id)
INNER JOIN $wpdb->term_taxonomy tt
ON (tr.term_taxonomy_id = tt.term_taxonomy_id)
WHERE
p.post_status = 'publish'
AND tt.taxonomy = %s
AND tt.term_id = %d;",
$taxonomy,
$term->term_id);
return $wpdb->get_var($st);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment