Extend search to all ACF fields

How can I extend WordPress search to all Advanced Custom Fields created?

To make ACF data available to wp_search, add this code to your plugin:

<?php
// search in all ACF Fields
add_filter('posts_join', 'wpster_acf_search_join' );
function wpster_acf_search_join( $join ) {
	global $wpdb;
	if ( is_search() ) {
		$join .=' LEFT JOIN '.$wpdb->postmeta. ' ON '. $wpdb->posts . '.ID = ' . $wpdb->postmeta . '.post_id ';
	}
	return $join;
}
add_filter( 'posts_where', 'wpster_acf_search_where' );
function wpster_acf_search_where( $where ) {
	global $pagenow, $wpdb;
	if ( is_search() ) {
		$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_distinct', 'wpster_acf_search_distinct' );
function wpster_acf_search_distinct( $where ) {
	global $wpdb;
	if ( is_search() ) {
		return "DISTINCT";
	}
	return $where;
}

?>

Submit a Comment

Your email address will not be published.