0

I have a custom 'pre_get_posts' function, that attaches meta_query:

function my_pre_get_posts($query)
 {
   $query_filters = array(
      'color' => 'color',
      'size' => 'size',
      'type' => 'type',
   );

  if (is_admin()) {

    return $query;

}


  $meta_query = $query->get('meta_query');
  if( isset($query->query_vars['post_type']) && $query->query_vars['post_type'] == 'project'){
    foreach ($query_filters as $key => $name) {
        if (empty($_GET[$name])) {
            continue;
        }
        $value = explode(',', $_GET[$name]);
        $meta_query = [[
            'key' => $name,
            'value' => $value,
            'compare' => 'IN',
        ]];
    }
}

if (!empty($meta_query)) {
    $query->set('meta_query', $meta_query);
}

return $query;
  }
add_action('pre_get_posts', 'my_pre_get_posts',10,1);

This solution works fine with a request like this:

https://mywebsite.com/?color=Black

Filters out the data correctly, but when i have multiple arguments it breaks:

https://mywebsite.com/?color=Black&type=Bold

and seems to filter out in-correctly

1
  • When you say 'it breaks', what precisely does happen? Do you get an error? It also looks like your code only supports one meta_query: if you have multiple parameters then the second one will overwrite the first one's meta_query, not combine with it. – Rup Dec 8 '20 at 17:45

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.