Johan Nordli
Johan Nordli

Reputation: 1230

Wordpress get post by tag name

I want to query posts by tag name and not by tag slug

I've tried this but it will only work with tag slug

$args = array( 'post_type' => "news_type", 'posts_per_page' => -1, 'tag' => "my tag" );

An alternative would be to get a tag by the tag name, and then get slug from the tag.

( I only have access to the tag name in my code)

Upvotes: 1

Views: 8547

Answers (1)

Pieter Goosen
Pieter Goosen

Reputation: 9941

Best way to achieve this is with a tax_query. You can either pass the term_id (which is the default), name or slug to the terms parameter

You can try something like this:

$args = array(
    'post_type' => 'news_type',
     'posts_per_page' => -1,
    'tax_query' => array(
        array(
            'taxonomy' => 'post_tag',
            'field'    => 'name',
            'terms'    => 'NAME OF THE TAG',
        ),
    ),
);
$query = new WP_Query( $args );

Upvotes: 6

Related Questions