I need to fetch all the posts with a specific tag, but I’m getting all the posts instead. My query works if I publish a post with the tag that I need and list all the posts with that tag, but when I publish a post with another tag, it’s fetching the newly published post.
This is my query:
$original_query = $wp_query;
$wp_query = null;
$args=array(
'posts_per_page' => -1,
'tag' => $post_tag
);
$wp_query = new WP_Query( $args );
$post_titles=array();
$i=0;
if ( have_posts() ) :
while (have_posts()) : the_post();
$post_titles[$i]=get_the_ID() ;
$i++;
endwhile;
endif;
$wp_query = null;
$wp_query = $original_query;
wp_reset_postdata();
2 Answers
It’s a lot easier to create a new WP_Query than it is to try clearing or overwriting the original.
If $post_tag is a tag slug, you could simply use:
<?php
$the_query = new WP_Query( 'tag='.$post_tag );
if ( $the_query->have_posts() ) {
echo '<ul>';
while ( $the_query->have_posts() ) {
$the_query->the_post();
echo '<li>' . get_the_title() . '</li>';
}
echo '</ul>';
} else {
// no posts found
}
/* Restore original Post Data */
wp_reset_postdata();