0

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()) : ?>
  <div>
    <?php while (have_posts()) : the_post(); ?>
      … //get the permalink, title etc...
    <?php endwhile; ?> 
  </div>
<?php endif; ?>

The post ID's are retrieved:

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

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

Would be very grateful for help!

0

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' ); ?>
<?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?> 
<div id="has-tags">
    <ul id="the-tags"><?php the_tags(); ?></ul>
  <?php the_content(); ?>
  <?php endwhile; endif; ?>
</div>
<?php
} else { 
// Whaterver else you're doing here.'
} ?>
| 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
0

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

<?php
  if(count($idspost)){
    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>";
  }
?>  
| improve this answer | |

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.