WordPress Multiple Category Search

The problem is that in a url the ‘+’ sign is equivalent to a space so that’s how PHP sees it.

If you use an action on parse_request you can make this work like so:

add_action( 'parse_request', 'category_search_logic', 11 );
function category_search_logic( $query ) {

    if ( ! isset( $query->query_vars[ 'cat' ] ) )
        return $query;

    // split cat query on a space to get IDs separated by '+' in URL
    $cats = explode( ' ', $query->query_vars[ 'cat' ] );

    if ( count( $cats ) > 1 ) {
        unset( $query->query_vars[ 'cat' ] );
        $query->query_vars[ 'category__and' ] = $cats;
    }

    return $query;
}

The above will get category ids passed in with ‘+’ in between them by splitting them on a space which is what PHP sees in the $_GET parameter.

If we have more than one item in the array it must be an ‘and’ style search so we can pass the array from splitting on the space into the 'category__and' query var which returns posts in all the specified categories.

Leave a Comment