wordpress trying to get posts by tag

wordpress trying to get posts by tag  using -'wordpress,tags'

I've written some code which automatically creates some posts and adds a tag to them.  I can see the tags in the 'All posts' admin panel and I can click on the posts 'Tag' link to get just those posts with the tags.

However, in a plugin that I'm writing using $wp_query no matter what parameters I pass in, I just get the complete list of posts back whether they have the tag that I am looking for or not.

Here's my code:

// Now retrieve all items matching this brand name . . .
$query=new WP_Query(array('posts_per_page=5', array('tag' => array($brand_name))));

// The Loop
while ( $query->have_posts() ) : $query->the_post();
    echo '<li>';
    echo '</li>';

// Reset Post Data

This produces 10 results when I've told it only to return 5.  In reality I should only get 2 posts back as that's the total number with the tag.

Looking around on the web there seems to be a lot of people having the same problem but no solutions.  I must have tried about 10 different ways of specifying the tag but the fact that the number of posts returned is wrong suggests I've either got something completely wrong or there is some kind of bug.  Wordpress version is 3.4.1 if it helps.

Can any Wordpress pro's shed light on this ?

Thanks in advance !

asked Oct 23, 2015 by ajit.chavhan
0 votes

2 Answers

0 votes

Try this

$original_query = $wp_query;
$wp_query = null;
$args=array('posts_per_page'=>5, 'tag' => $brand_name);
$wp_query = new WP_Query( $args );
if ( have_posts() ) :
    while (have_posts()) : the_post();
        echo '
  • '; the_title(); echo '
  • '; endwhile; endif; $wp_query = null; $wp_query = $original_query; wp_reset_postdata();
    answered Oct 23, 2015 by gauravg.gwl
    0 votes

    Answer was found here - https://codex.wordpress.org/Template_Tags/get_posts

    Following example displays posts tagged with 'jazz', under 'genre' custom taxonomy, using 'tax_query'

    $args = array(
        'tax_query' => array(
                'taxonomy' => 'genre',
                'field' => 'slug',
                'terms' => 'jazz'
    $postslist = get_posts( $args );

    So for you it will be

    $args = array( 
            'posts_per_page' => 5,
            'tax_query'      => array(
                    'taxonomy'  => 'post_tag',
                    'field'     => 'slug',
                    'terms'     => sanitize_title( $brand_name )
    $postslist = get_posts( $args );
    answered Oct 23, 2015 by android_master