I have assigned a custom taxonomy named Highlight
to posts and I have added a term to it named Featured
.
Whenever I want to feature a post, I simply assign it to featured.
To each author, I want to display their count of total amount of featured posts.
So the function the_author_posts()
will display count of total posts. I want to display count of total posts that were featured to the author.
How can I do this?
1 Answer
/**
* Get the author post count for a tax query.
*
* @link http://wordpress.stackexchange.com/q/159160/1685
*
* @param array $tax_query
* @return int
*/
function wpse_159160_get_author_posts_by_tax( $tax_query ) {
global $wpdb;
$where = get_posts_by_author_sql( 'post', true, get_post()->post_author );
$tax_query = new WP_Tax_Query( $tax_query );
$sql = $tax_query->get_sql( $wpdb->posts, 'ID' );
return ( int ) $wpdb->get_var( "SELECT COUNT(*) FROM $wpdb->posts {$sql['join']} $where {$sql['where']}" );
}
And in use:
$count = wpse_159160_get_author_posts_by_tax(
array(
array(
'taxonomy' => 'highlight',
'terms' => 'featured',
'field' => 'slug',
)
)
);
echo "$count Featured Posts";
If you wanted less control with the function (& neater template code), you could hardcode the $tax_query
argument inside the function and just call it without arguments elsewhere.