WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

On our current site we have different company profiles. Some companies have blog posts that display on their profile and some don't. Their is an h2 tag above posts that is in the page template then the code to bring in the posts. The code looks like this.

<h2>Recent Blog Articles</a></h2>


 echo get_related_author_posts();

I am trying to find a way so that if their are no posts for the company the h2 tag will not show up. The code in the functions file is

function get_related_author_posts() {
    global $authordata, $post;

    $authors_posts = get_posts( array( 'author' => $authordata->ID, 'post__not_in' => array( $post->ID ), 'posts_per_page' => 5 ) );

    $output = ' <ul style="list-style: none;">';
    foreach ( $authors_posts as $authors_post ) {
        $output .= '<li><a href="' . get_permalink( $authors_post->ID ) . '">' . apply_filters( 'the_title', $authors_post->post_title, $authors_post->ID ) . '</a></li>';
    $output .= '</ul>';

    return $output;
share|improve this question
Could you please show us more of the code? I guess, the heading is inside the loop (i.e., while ( have_posts() )). So, if there are no posts, the heading won't be echoed. Or am I mistaken? – tfrommen Mar 7 '13 at 17:58
Incidentally, you should fix that closing anchor tag in your h2. – vancoder Mar 7 '13 at 18:02

Put your <h2> tag after the call to get_related_author_posts(). For example...

$rap = get_related_author_posts();

if (!empty($rap)) {
  echo '<h2>Recent Blog Articles</a></h2>'; // <- broken anchor tag !!!
  echo $rap;
  // and so on

But you will need to make get_related_author_posts() return false if there are no posts.

function get_related_author_posts() {
    global $authordata, $post;

    $authors_posts = get_posts( array( 'author' => $authordata->ID, 'post__not_in' => array( $post->ID ), 'posts_per_page' => 5 ) );
    if (empty($author_posts)) return false;
    // and the rest of the function
share|improve this answer

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

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