0

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!

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)
);
|improve this answer|||||
  • What if I need to query by : 's' => 'some-keyword' or 'post_tag' => 'some_tag' – Bruno Rodrigues Jun 9 '17 at 21:00
  • I have updated my answer, funny but it's not so trivial as I thought at first. – Picard Jun 9 '17 at 21:50
  • Yeah, that would be wiser - one query instead of three :) – Picard Jun 13 '17 at 6:04

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.