Display Posts by Tag WordPress

WP_Query is playing major role in WordPress. It has many different parameters usage according to the requirement. Have you ever wanted to query through posts which has associated with certain tags. Here we going to see how to use Tag Parameter in the query. Lets see WP Query by tag in WordPress. Dive into display posts by tag wordpress.

Available Tag Parameters

  • tag (string) – use tag slug.
  • tag_id (int) – use tag id.
  • tag__and (array) – use tag ids.
  • tag__in (array) – use tag ids.
  • tag__not_in (array) – use tag ids.
  • tag_slug__and (array) – use tag slugs.
  • tag_slug__in (array) – use tag slugs.

We can gone through one by one.

Using ONE Tag

Can query through the specific tag slug. So, all the posts associated with the slug are in return.

$tag_query = new WP_Query( array( 'tag' => 'wordpress' ) );

As well can use tag id instead of using the tag slug.

$tag_query = new WP_Query( array( 'tag_id' => 90 ) );

Using several Tags

Getting posts from multiple tags also not difficult. Just refer the code below. It is nothing complicated just pass the tag slug using comma separated. This will return posts from either tag slug is using.

$tag_query = new WP_Query( array( 'tag' => 'wordpress,php' ) );

If you want to get all posts which have all tags we are passing through the array. Here is the solution. This will return all posts which have both wordpress and php tags. If you need more to add no worries add in the query by separating plus(+) mark.

$tag_query = new WP_Query( array( 'tag' => 'wordpress+php' ) );

Multiple Tag handling



Display posts by tag ids

Display posts by tag ids also in same way. You just need to change the tag parameter name. This will display all posts which are tagged with 13 and 27 tag ids.

$tag_query = new WP_Query( array( 'tag__and' => '13, 27' ) );

Display posts from either tag

To display posts from either tag you need to use tag__in instead of tag__and . This will return posts from either tag id.

$tag_query = new WP_Query( array( 'tag__in' => '13, 27' )

Display posts after excluding some tag ids

To display posts after excluding some tag ids. The option is there. So, you need to use tag__not_in to exclude tag ids from the query. This will return all posts except tag ids 13 and 27.

$tag_query = new WP_Query( array( 'tag__not_in' => '13, 27' ) );

Display all posts tagged with specific tag name

This will display all posts tagged with following tag slugs.

$tag_query = new WP_Query( array( 'tag_slug__and' => 'wordpress, php' ) );

Display posts from either tag slug

This will display posts from either tag with following tag slugs.

$tag_query = new WP_Query( array( 'tag_slug__in' => 'wordpress, php' ) );

Hope you’ll enjoy this and you will improved your knowledge about the WP_Query arguments.

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *