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 1

 * 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(
            '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.

  • To clarify. Can I change the get_post()-> post_author to a custom user id like current user's id?
    – Jocob
    Commented Aug 26, 2014 at 17:24
  • 1
    Of course - just use get_current_user_id() instead. If you want to vary it, add a $user_id argument to the function and then call it as required. Commented Aug 26, 2014 at 17:25

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.