<?php
// Function to do the term count or post count calculations:
function get_post_count_for_term_and_post_type( $term_id, $taxonomy, $post_type ) {
$taxquery = array();
if ($term_id && $taxonomy) {
$taxquery = array(
array(
'taxonomy' => $taxonomy,
'field' => 'id',
'terms' => $term_id,
)
);
}
// Build the args
$args = array(
'post_type' => $post_type,
'posts_per_page' => -1,
'tax_query' => $taxquery
);
// Create the query
$query = new WP_Query( $args );
$total = $query->found_posts;
// Return the count
return $total;
}
// Get the number of posts for the category with id 17. Fill in the term id, taxonomy and post type:
$termcount = get_post_count_for_term_and_post_type(17,'category','post');
// Get the total number of posts for the 'post' post type. Fill in empty strings for the term id and taxonomy, and the post type in the last argument:
$postcount = get_post_count_for_term_and_post_type('','','post');
// Percentage of posts with term 17:
$percentage = $termcount / $postcount * 100 .'%';
echo $percentage;