php - How to hide div with text inside if loop returns no posts?
Get the solution ↓↓↓First loop retrieves posts related to current post based the primary tag. The second loop, which is displayed below, gets posts based on the secondary tag. If a post is displayed by the first loop it is excluded from being retrieved by the second loop so that there are no duplicate posts.
If there are no posts matching the current post by tag, nothing is shown. Here is where I have a problem. I need the extra<div id="relatedheader">
element inside (or outside) of the<ul>
to display the header text "Related posts" (with some style applied like background color). If there are no posts matching it doesn't display but at the moment it returns the header "Related posts" for every post retrieved by the query. I can see that it is echoed out for every post displayed at the moment. I can't see how I can alter the code to make it show only once above the posts?
<ul id="related">
<?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'=>3, //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)) {; echo '<div id="relatedheader">Related posts</div>'; ?>
<li><a href="<?php the_permalink() ?>" rel="bookmark" title="Permanent Link to <?php the_title_attribute(); ?>"><?php the_title(); ?></a></li>
<?php } endwhile;
}
}
?></ul>
Answer
Solution:
Separate your logic from your presentation. Move all your code that gathers posts and related posts to the top, or to a different file or function, and store the data in an array. Then, when you get to the part where you output your HTML, you already know whether there are related posts, and you can use an if condition to decide whether to output the header.
Share solution ↓
Additional Information:
Link To Answer People are also looking for solutions of the problem: http failure during parsing for
Didn't find the answer?
Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.
Similar questions
Find the answer in similar questions on our website.
Write quick answer
Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.