Take the tour ×

In a single post template I am trying to output some header text in a <div> and display links to related posts in a <ul> if related posts exist (based on tags). If there are no posts, nothing should be displayed. $idspost[] = $post->ID gets the posts which should be displayed. The loop is one of a series of loops and the retrived post ID's are also passed on to the next loop in order to avoid duplicate posts showing up. All works well so far. I have echoed out the ID's to test, but with my basic skills I don't realize how I will display the <div>,<ul> and retrieve the post ID's in the standard way:

<?php if (have_posts()) : ?>
      … //get the permalink, title etc...
    <?php endwhile; ?> 
<?php endif; ?>

The post ID's are retrieved:

    $tags = wp_get_post_tags($post->ID);
    if ($tags) {
      $second_tag = $tags[1]->term_id;
        'tag__in' => array($second_tag),
        'showposts'=>5, //Display this number of related posts
      $my_query = new WP_Query($args);
      if( $my_query->have_posts() ) {
          if (!in_array($post->ID, $ids)) 
          {; $idspost[] = $post->ID; ?>

    <?php }
        $ids[]= $post->ID; 
        $idspost[] = $post->ID;

Would be very grateful for help!

share|improve this question
add comment

2 Answers

You can use the has_tag function in a conditional statement to achieve what you want. Take a look at the codex page here: Function Reference/has tag. This isn't 100% tailored to your specific question, but you should see how it's working and adjust for your specific task:

<?php if( has_tag() ) { ?>
<?php query_posts( 'cat=1&posts_per_page=5' ); ?>
<div id="has-tags">
    <ul id="the-tags"><?php the_tags(); ?></ul>
  <?php the_content(); ?>
  <?php endwhile; endif; ?>
} else { 
// Whaterver else you're doing here.'
} ?>
share|improve this answer
Thank you Jeremy! I found a working solution by using an if condition and foreach to grab the data stored in the $idspost array –  sarytash Feb 24 '12 at 14:07
add comment
up vote 0 down vote accepted

To get the data in the array to output as posts I did the following:

    echo "<div>Related posts<ul>";
    foreach($idspost as $id){
       echo '<li><a href="'.get_permalink( $id ).'">'.get_the_title( $id ).'</a></li>';
    echo "</ul></div>";
share|improve this answer
add comment

Your Answer


