I store post IDs in an array. I would like to loop through the array and display the IDs within a <div>
containing <p>
and <ul>
tags, but only when at least one ID is in the array. If the array is empty no html can be returned. This implies that I should use some kind of if statement before the loop. Needless to say, my php skills are pretty basic and after two days of trying hard I am getting nowhere. Grateful for help!
My code (using Wordpress)
$postids = array();
...
$postids [] = $post->ID; //stores the post IDs in the array
Here is an update. I apologize for posting all this code as its quite messy with many things going on. It's the second loop of three (or more). The IDs displayed in a near identical first loop have been passed on. Only those IDs which have not been retrieved by the previous loop are displayed in order not to show any duplicate posts.
I have tried to remove all html markup and query the $postids with a new WP_Query after but that retrieves all posts I have ever created. I am pretty sure that's the right way to continue although I am obviously doing something wrong.
<?php
$tags = wp_get_post_tags($post->ID);
if ($tags) {
$first_tag = $tags[1]->term_id;
$args=array(
'tag__in' => array($first_tag),
'post__not_in' => array($post->ID),
'showposts'=>5, //Display this number of related posts
'ignore_sticky_posts'=>1
);
$postids = array();
$my_query = new WP_Query($args);
if( $my_query->have_posts() ) {
echo '<ul id="relatedposts">';
while ($my_query->have_posts()) : $my_query->the_post(); if (!in_array($post->ID, $ids)) {; $postids [] = $post->ID; ?>
<li><a href="<?php the_permalink() ?>" rel="bookmark" title="Permanent Link to <?php the_title_attribute(); ?>"><?php the_title(); ?></a></li>
<?php }
$ids[]= $post->ID;
endwhile;
}
}
?>
</ul>
<?php if ($postids){ //$postids has at least one value set
echo '<div>Related posts</div>'; //Outputting the header text. This works! If there are no IDs in the array nothing is shown.
};
?>
<?php if (have_posts()) : ?> <div><p>header text</p> <?php while (have_posts()) : the_post(); ?> do stuff... <!--get the permalink, title etc...--> <?php endwhile; ?> </div> <?php endif; ?>
Without any luck though! – sarytash Feb 19 '12 at 19:47