wp query – filtering product search results using tags

Initially I tried to just add the tag to the url: https://test.com/?s=test&post_type=product&tag=slug

Despite there being products matching these filters, it returned 0 results. I also tried this with tag id instead of slug, but to no avail. Then I tried to add a filter to the query request:

function filter_search( $query ) {
    if( $query->is_search ) {
        if ( isset($_GET['tag_id']) ){
            $query->set( 'tag_id' , $_GET['tag_id'] );
        }
    }
    return $query;
}
add_filter( 'pre_get_posts' , 'filter_search' );

I tried changing the tag, tag_in and tag_id fields, but none seemed to work. I also tried casting the GET request for tag_id to an int, once again with no change.

If anyone has a solution to fix this, it would be really appreciated.

Leave a Comment