Advanced Custom Fields Checkbox Query not Working

For some websites I own, I would like my visitors to be able to filter on different Advanced Custom Fields on WordPress Archive pages. To create such filters I used this tutorial.

However, I can’t seem to get the filter working the way I want. Here’s my code for the archive page.

Read More
function my_pre_get_posts( $query ) {

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

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

// loop over filters
foreach( $GLOBALS['my_query_filters'] as $key => $name ) {

    // continue if no values found in url
    if( empty($_GET[ $name ]) ) {           
        continue;
    }

    // get the values for this filter
    $value = explode(',', $_GET[ $name ]);

    // append meta query
$meta_query[] = array(
    'key'       => $name,
  'value'       => $value,
  'compare' => 'IN'
);       
}   

// update meta query
$query->set('meta_query', $meta_query);

//print_r($query);  

echo $GLOBALS['wp_query']->request;

Here’s the SQL code it spits out on running:

SELECT SQL_CALC_FOUND_ROWS wp_posts.ID
FROM wp_posts
INNER JOIN wp_term_relationships ON ( wp_posts.ID = wp_term_relationships.object_id ) 
INNER JOIN wp_postmeta ON ( wp_posts.ID = wp_postmeta.post_id ) 
WHERE 1 =1
AND (
wp_term_relationships.term_taxonomy_id
IN ( 2, 9, 11 )
)
AND (
(
wp_postmeta.meta_key =  'payment_method'
AND CAST( wp_postmeta.meta_value AS CHAR ) 
IN (
'Delta',  'Visa'
)
)
)
AND wp_posts.post_type =  'post'
AND (
wp_posts.post_status =  'publish'
OR wp_posts.post_status =  'private'
)
GROUP BY wp_posts.ID
ORDER BY wp_posts.post_date DESC 
LIMIT 0 , 100

However, this SQL statement returns 0 results. I also ran this query:

SELECT * 
FROM  `wp_postmeta` 
WHERE  `meta_key` =  'payment_method'
LIMIT 0 , 30

This does return results. Meta value for these results is something like:

a:3:{i:0;s:5:"Delta";i:1;s:4:"Visa";i:2;s:11:"Visa(debit)";}

I guess there’s something wrong with the generated query, but I have no idea what exactly. I hope someone here can help me out. Not sure if worth noting, but running the first bit of code also messes up my theme as it won’t load the topmenu when for example ?payment_method=Delta,Visa is in the url.

Thanks in advance.

Related posts

1 comment

  1. Got it working! Here’s the code I now use to append the meta_query to the query.

    $values_to_search = explode(',', $_GET[ $name ]);
    $meta_query = array('relation' => 'OR');
    foreach ($values_to_search as $value) {
        $meta_query[] = array(
            'key'       => $name,
            'value'     => $value,
            'compare'   => 'LIKE',
        );
    } 
    

    I’m not sure why this works and the previous “solution” did not. If you have any ideas, please let me know!

Comments are closed.