Search code examples
wordpresswordpress-rest-api

Find wordpress post by search term OR tag


I'm trying to write an query that should find a post by search-term or tag-name. But when i add the tag name the search stops working.

$mainQuery = new WP_Query(array(
    'post_type' => array('coworker', 'post', 'page', 'news'),
    's' => sanitize_text_field($data['term']),
    'relation' => 'OR',
    'tag' => array(
        'tag' => sanitize_text_field($data['term'])
    )
));

What have i done wrong here?


Solution

  • There are two issues with your code:

    1. WP_Query does not accept the relation parameter, this is only accepted in the tax_query and meta_query arguments.
    2. The tag parameter does not require you wrap your argument in an array, it accepts a variety of names, depending on what argument(s) you are passing.

    Depending on your implementation, you likely need to run two queries and merge the results, as you want either OR result.