Support

Account

Home Forums Feedback Using pre_get_posts to filter only posts that include all values

Solved

Using pre_get_posts to filter only posts that include all values

  • Hello, I have everything setup and working as far as filtering my custom post types in archives. Right now though, when I check multiple values it will return any post that has any of the values. So if I check ‘female’ with ‘black hair’ it should only bring up females with black hair not any post that has either of those values. So if I check ‘female’ that has ‘black hair’ and is ‘caucasian’ and lives in ‘St. Louis’. the only posts that should show up are ones that include all those values.

    Here is my pre_get_posts function I have so far:

    function my_pre_get_posts( $query ) {

    // bail early if is in admin
    if( is_admin() ) {
    return $query;
    }

    // bail early if not main query
    // – allows custom code / plugins to continue working
    if( !$query->is_main_query() ) return $query;

    if (isset($query->query_vars[‘post_type’]) && $query->query_vars[‘post_type’] == ‘models’) {

    foreach ($GLOBALS[‘my_query_filters’] as $key => $name) {

    $values = explode(‘,’, $_GET[$name]);

    if (isset($_GET[$name])) {

    $query->set(‘meta_key’, $name);
    $query->set(‘meta_value’, $values);
    }
    }
    }

    return $query;
    }

    Thanks in advance

  • Please disregard my post. I have actually figured this out. thanks

  • FYI function should look like this:

    // bail early if is in admin
    if( is_admin() ) {
    return;
    }

    // bail early if not main query
    // – allows custom code / plugins to continue working
    if( !$query->is_main_query() ) return;

    // get meta query
    $meta_query = $query->get(‘meta_query’);

    $meta_query = array(
    ‘relation’ => ‘AND’,
    );
    foreach ($GLOBALS[‘my_query_filters’] as $key => $name) {

    if (!empty($_GET[$name])) {

    $values = explode(‘,’, $_GET[$name]);

    $meta_query[] = array (
    ‘key’ => $name,
    ‘value’ => $values,
    ‘compare’ => ‘IN’,
    );

    }
    }

    $query->set(‘meta_query’, $meta_query);

    return;

Viewing 3 posts - 1 through 3 (of 3 total)

You must be logged in to reply to this topic.

We use cookies to offer you a better browsing experience, analyze site traffic and personalize content. Read about how we use cookies and how you can control them in our Cookie Policy. If you continue to use this site, you consent to our use of cookies.