16
votes

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>';
    the_title();
    echo '</li>';
endwhile;

// Reset Post Data
wp_reset_postdata();

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 !

3

3 Answers

20
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(
        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(
            array(
                'taxonomy'  => 'post_tag',
                'field'     => 'slug',
                'terms'     => sanitize_title( $brand_name )
            )
        )
    );

$postslist = get_posts( $args );
18
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 '<li>';
        the_title();
        echo '</li>';
    endwhile;
endif;

$wp_query = null;
$wp_query = $original_query;
wp_reset_postdata();
0
votes

In your code, try:

$query=new WP_Query(array('posts_per_page=5', 'tag' => $brand_name));

instead of:

$query=new WP_Query(array('posts_per_page=5', array('tag' => array($brand_name))));

For further details, see https://codex.wordpress.org/Class_Reference/WP_Query#Tag_Parameters (and as mentioned on a recent duplicate post).

Note: $brand_name could be an array of strings, or comma separated values, etc., and the above code should work.

Alternatively, try:

$myPosts = get_posts(array('tag' => $brand_name));

See https://codex.wordpress.org/Template_Tags/get_posts