Home › Forums › ACF PRO › Search in post object field by post_id › Reply To: Search in post object field by post_id
I took me quite some time to figure out on how to do this – so I’ll post my solution to hopefully help somebody else who’s having the same Problem:
My requirement was to be able to search not only for the title but an ACF field (a number in my particular case) as well.
I stumbled across the second link from Johns answer before and was able to use it for the search functionality of the edit screens of my custom posts – but it was not working for the post object ACF field – since $is_search is not set on ajax requests/queries.
I tried to find another way to identify the query from the post object field and in the end I ended up with the following:
function cf_post_object_query( $args ) {
// Set a query variable to identify the post object query
$args['is_acf_query'] = true;
// return
return $args;
}
// filter for a specific field
add_filter('acf/fields/post_object/query', 'cf_post_object_query');
In combination with Adams filters (slightly customized):
function cf_search_where( $where, $wp_query ) {
global $pagenow, $wpdb;
$is_acf = isset( $wp_query->query['is_acf_query'] ) ? $wp_query->query['is_acf_query'] : false;
if ( is_search() || $is_acf ) {
$where = preg_replace(
"/\(\s*".$wpdb->posts.".post_title\s+LIKE\s*(\'[^\']+\')\s*\)/",
"(".$wpdb->posts.".post_title LIKE $1) OR (".$wpdb->postmeta.".meta_value LIKE $1)", $where );
}
return $where;
}
add_filter( 'posts_where', 'cf_search_where', 10, 2 );
(You’d need to do this for all three of them I suppose)
But it finally works, I can search for the acf field and the title in the post object field.
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.