Home › Forums › Feature Requests › Search Form for ACF for Custom Post Types › Reply To: Search Form for ACF for Custom Post Types
When dealing with any type of ACF field that does not store simple text values in the database, you will always have some problems, unless the plugin you’re using is built specifically to work with ACF.
The fields that do not cause issues are the ones listed under “Basic” and a few others like single select fields, radio button fields, and true false fields.. maybe a couple of others.
To use other types of fields in a standard WP_Query bases search application what you need to do is build filters, using the acf/save_value hook, and store the values into the meta table in a form that WP can easily search and then use these fields for the queries.
As a quick example, let’s say that you have a checkbox field. This type of field stores a serialized array. This is difficult to search using a standard WP query, the the results can be inconsistent. But if you take the value and store in in the way that WP does, with each of the values having a separate row in the database then it becomes much easier.
// add a filter to convert the value of a checkbox field
add_filter('acf/update_value/name=my_checkbox_field', 'convert_checkbox_to_queryable_form', 10, 3);
function convert_checkbox_to_queryable_form($value, $post_id, $field) {
$queryable_name = 'queryable_my_checkbox_field';
// first remove all of the values from the new field
delete_post_meta($post_id, $queryable_name);
if (empty($value)) {
// there is not value so there's no reason to continue
return $value;
}
// now we can loop over the checkbox array
// and store them so the values are easier
// to use in WP_Query()
foreach ($value as $single) {
// add the post meta
// and allow it to have multiple values
add_post_meta($post_id, $queryable_name, $single, false);
}
// make sure you return the original value
return $value;
} // end function
With a function like this in place you can use the new field name and it makes it much simpler for meta_query.
Welcome to the Advanced Custom Fields community forum.
Browse through ideas, snippets of code, questions and answers between fellow ACF users
Helping others is a great way to earn karma, gain badges and help ACF development!
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 Privacy Policy. If you continue to use this site, you consent to our use of cookies.