Ryan Achten
Ryan Achten

Reputation: 525

Advanced Custom Field checkbox query not working

I am using an Advanced Custom Field to allocate a custom field to posts. This field is then used by a filtering system to filter posts using a custom query (via the pre_get_posts action). The other query arguments are working fine, except for the one which relies on ACF’s field.

The current query arguments of the field’s meta_query have been constructed according to the ACF documentation for the field (hence the quotation marks surrounding the value).

Can anyone advise me as to where this is going wrong? The query doesn’t seem to return any posts based on the values I am passing to the query.

Query arguments:

$courses = get_query_var('courses');
if ($courses) {
    $query->set('meta_query', array(
            array(
                'key' => 'course_check',
                'value' => '"'.$courses.'"', //i.e mdia-403
                'compare' => 'LIKE'
            ),
        )
    );
}

Upvotes: 0

Views: 2103

Answers (2)

Ryan Achten
Ryan Achten

Reputation: 525

Found the cause of this issue by print_r’ing the entire query and inspecting what was actually going on - had done this a number of times, but overlooked the following detail:

The issue here wasn’t actually due to the checkbox meta_query, but a conflict between the get_query_var term (‘courses’) and a custom taxonomy whose slug is also ‘courses’.

When the query was executed, the query seemed to be querying for posts associated with both the custom taxonomy and the selected checkbox value, yielding no results.

Renaming the name attr to something other than courses then reconfiguring the registered query var and meta_query fixed this issue.

Upvotes: 0

Timo L
Timo L

Reputation: 46

ACF stores checkbox values in array, that's the reason your code is not working.

See working example here: https://support.advancedcustomfields.com/forums/topic/wp_query-using-meta_query-for-an-acf-checkbox-field/

Upvotes: 1

Related Questions