If the contributor has already published two or more posts I show a maximum of 5 of them in the post-single.php using this code

<?php echo do_shortcode('[latestbyauthor show="5"]'); ?>

I have a text that introduces the code (other posts by the same author)

This works fine if the contributor really has published 2 or more article but totally uselless if he has just one post.

What I'm looking is a way to hide the text before the code by checking the total number of posts published, if 1 then hide and if 2 then show.

Is it possible? Thanks!


Simpler than using the $wpdb class would be to use count_user_posts(). For instance:

$min_posts = 2;
if( count_user_posts( $post->post_author ) >= $min_posts ) {
    // display the user's posts

This assumes you're in The Loop, or at the very least that $post is a WordPress Post object.

[above edited 2013-03-19 11:30 AM CDT]

Note that if you're trying to count custom post types (and possibly pages, though I'm not sure), you'll need to use some $wpdb magic, but there's a code sample available at the Codex page for count_user_posts() (linked above).

  • I'm not good at php... I tried <?php $min_posts = 2; if( count_user_posts( $author_id ) > $min_posts ) { echo "Other posts from the same user"; // display the user's posts } ?> with no luck as it keeps showing the text even if the author has published only one post... – user27309 Mar 18 '13 at 14:58
  • What are you using as $author_id? If it's an un-initialised value, it may be comparing in correctly and giving a false positive. – David Gard Mar 18 '13 at 17:02
  • I've updated my code sample, replacing $author_id with $post->post_author, and also changing the > comparison to >= so that you'll catch authors with exactly 2 posts. – Pat J Mar 19 '13 at 16:31

You could run a query to grab an array of the number of posts by each author, and then check that array. This is untested, so may need tweeking (a Google search of 'mysql count occurrences of value' should also yield some results.

$query = 'SELECT post_author, COUNT(*) as count FROM wp_posts GROUP BY post_author ORDER BY count DESC'
$author_count = $wpdb->get_col($query);

Then, when you are checking the number of posts by that author -

if($author_count($author_id)) > 1) : // Where $author_id is the ID of the Author being shown
    // Do whatever here...

Finally, if you get an error, you may need to add global $wpdb; just before the $query = ... line

  • Forgive me but running a query seems to be beyond my possibilities... I hoped it was just a matter of adding that code in functions.php... – user27309 Mar 18 '13 at 15:02

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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