Wordpress: trying to get posts by tag

I wrote code that automatically creates some posts and adds a tag to them. I can see the tags in the "All Messages" administration panel, and I can click the "Tag" link for messages to receive only those messages with tags.

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

Here is 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 gives 10 results when I said this only for return 5. Actually, I should only get 2 messages back, as a total with the tag.

Looking around the Internet, it seems that many people have the same problem, but no solutions. I must have tried about 10 different ways to specify a tag, but the fact that the number of returned messages is incorrect suggests that I have something completely wrong or there is some kind of error. Wordpress version 3.4.1 if that helps.

Can any Wordpress shed some light on this?

Thanks in advance!

+8
tags wordpress
source share
3 answers

try it

 $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(); 
+13
source share

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

The following example displays messages tagged with 'jazz', in the 'genre' section a 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 ); 
+12
source share

In your code try:

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

instead:

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

See https://codex.wordpress.org/Class_Reference/WP_Query#Tag_Parameters for more details (and as mentioned in a recent duplicate post).

Note. $ brand_name can be an array of strings or values โ€‹โ€‹separated by commas, etc., and the code above should work.

Alternatively try:

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

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

0
source share

All Articles