wp query - WP_Query by keyword OR post tag

admin2025-06-05  10

Is there any 'native' way to query by keyword or post tag?

If not, how can I write a GOOD SQL query to retrieve the data correctly?

Thanks in advance!

Is there any 'native' way to query by keyword or post tag?

If not, how can I write a GOOD SQL query to retrieve the data correctly?

Thanks in advance!

Share Improve this question asked Jun 9, 2017 at 19:51 Bruno RodriguesBruno Rodrigues 1851 silver badge10 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 1

Depending what you want to achieve, the most simple way taken from Wordpress documentation looks like below.

Displays posts tagged with "bob", under "people" custom taxonomy:

$args = array(
    'post_type' => 'post',
    'tax_query' => array(
        array(
            'taxonomy' => 'people',
            'field'    => 'slug',
            'terms'    => 'bob',
        ),
    ),
);
$query = new WP_Query( $args );

Check the documentation link - you'll find more advanced examples.

Update:

If you'd like to query actually for both 'keyword' or 'tag'...

It's funny - I did some research and it turns out that it isn't so trivial in Wordpress.

The most clean looking, native solution I found uses three queries. The first two get the ids - one by tag and the other by keyword, and then the third make the final query.

$set1 = new WP_Query( array('
                    'fields'=> 'ids',
                    'post_type' => 'post',
                    'tax_query' => array(
                        array(
                            'taxonomy' => 'people',
                            'field'    => 'slug',
                            'terms'    => 'bob'
                        )
                    )
                )
);
$set2 = new WP_Query( array(
                    'fields'=>'ids',
                    'post_type' => 'post',
                    's' => 'News')
);

$combined_ids = array_merge($set1->posts, $set2->posts);
$combined_ids = array_unique($combined_ids);

$combines_sets = new WP_Query(array(
                            'post__in' => $combined_ids)
);
转载请注明原文地址:http://conceptsofalgorithm.com/Algorithm/1749105039a316403.html

最新回复(0)