Complex queries in WordPress with WP_Query

August 12th | By | Back to Blog

WordPress query class is a well documented class that allows you to query the database and filter results for all types of taxonomies within the system that offers a lot of flexibillity.

On a recent project a client has asked us to create a filterable search page based on groups of tags.
The search page was consisted of

<fieldset>

each had it’s own

<input type="checkbox"/>

with the appropriate tag.
The conditions were, Find the tags that are checked in each fieldset (IN relation) and that also have the other tags from the other field sets (AND relation).

Breaking down the query it would be something of the sort

SELECT * FROM wp_posts WHERE tags IN (fieldset 1 tags) AND tags IN (fieldset 2 tags) ...

But we all know that WordPress adds some complexity to that, this complexity is solvable with WP_Query.

Say that we send a form with each one of the tag sets like this

$_POST['fieldsets'] = array(
  0 => array(1, 2, 3, 4),
  1 => array(5, 6, 7, 8),
  2 => array(9, 10, 11, 12)
); // IDs of tags

Using WP_Query we came up with this solution

    $tax_query = array(
        'relation' => 'AND'
    );

    foreach ($_POST['fieldsets'] as $tag_array) {
        $tax_query[] = array(
            'taxonomy' => 'post_tag',
            'field' => 'id',
            'terms' => $tag_array,
            'operator' => 'IN'
        );
    }

    $posts = array(
        'posts_per_page' => 20,
        'post_type' => 'post',
        'tax_query' => $tax_query
    );

Good luck WP_Querying!