Here it is:
I want to filter my post based on category (Party)
If the post with category Party has tag which is ‘event’, it is the one that will display
If there is no ”event’ tag, only the recent post of Party category will display
here’s my code:
<?php
$post_cat = array(
'posts_per_page' => '1',
'cat' => '3'
);
$post_tag = array(
'posts_per_page' => '1',
'cat' => '3',
'tag' => 'event'
);
$catquery = new WP_Query( $post_cat );
$tagquery = new WP_Query( $post_tag );
if(has_tag()) :
while($tagquery->have_posts()) : $tagquery->the_post();
else if(has_category()) :
while($catquery->have_posts()) : $catquery->the_post();
else
?>
<?php $backgroundImg = wp_get_attachment_image_src( get_post_thumbnail_id($post->ID), 'full' );?>
<div class="blog-post-recent" style="background-image: url('<?php echo $backgroundImg[0]; ?>');">
<div class="wrap">
<div class="blog-post-content">
<div class="blog-post-inner-content">
<?php the_category();?>
<div class="blog-post-title"><a href="<?php the_permalink() ?>"><?php the_title( '<h2>', '</h2>' ); ?></a></div>
<div class="post-date"><?php the_date('F j, Y'); ?></div>
<?php the_excerpt(); ?>
<a class="blog-post-btn" href="<?php the_permalink() ?>"> Read More...</a>';
</div>
</div>
</div>
</div>
<?php endif;
wp_reset_postdata();
?>
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
The PHP while command doesn’t work like that, it needs to start and end in the same code block. You can’t start it inside one if then end it somewhere else (although that would be nice!)
What you can do is test have_posts before you start the while loop, and then keep which ever query you want in a new variable. So I think you want something like this. I’m assuming your two $post_cat and $post_tag searches do what you want for these two cases – i.e. $post_tag will be empty if there is nothing with this tag, and $post_cat gets what you want.
This code is untested but should do what you want. HTH
<?php
// Args to get what we want for the category
$catArgs = array(
'posts_per_page' => '1',
'cat' => '3'
);
// Args to get one post with tag event
$tagArgs = array(
'posts_per_page' => '1',
'cat' => '3',
'tag' => 'event'
);
$tagQuery = new WP_Query( $tagArgs );
// if there's something in the tagquery we'll use it, otherwise we'll use the other query
if ($tagQuery->have_posts()) {
$loopQuery = $tagquery;
} else {
$loopQuery = new WP_Query( $catArgs );
}
while ($loopQuery->have_posts()): $loopQuery->the_post();
?>
<b>loop stuff here</b>
<?php
endwhile;
?>
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0