Archived topic
How can I include Advanced Custom Fields data in Search Results?
5 replies · Started by Denise on September 2, 2018
Hi GP Friends,
I am using Advanced Custom Fields. When I add the search function to the menu, the search results are not able to search the custom fields. Is there a way to add this functionality in Generate Press? I do not want to have to use a plug-in such as Relevanssi, etc..
The code I'm testing is pasted below. It's from https://adambalee.com/search-wordpress-by-custom-fields-without-a-plugin/
Is something like this what you would recommend? Or is there a better way to add searching for advanced custom fields?
Thanks.
Denise
----------------------------
<?php
/**
* Join posts and postmeta tables
*
* http://codex.wordpress.org/Plugin_API/Filter_Reference/posts_join
*/
function cf_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_join', 'cf_search_join' );
/**
* Modify the search query with posts_where
*
* http://codex.wordpress.org/Plugin_API/Filter_Reference/posts_where
*/
function cf_search_where( $where ) {
global $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_where', 'cf_search_where' );
/**
* Prevent duplicates
*
* http://codex.wordpress.org/Plugin_API/Filter_Reference/posts_distinct
*/
function cf_search_distinct( $where ) {
global $wpdb;
if ( is_search() ) {
return "DISTINCT";
}
return $where;
}
add_filter( 'posts_distinct', 'cf_search_distinct' );
Looks like we found the same thread: https://support.advancedcustomfields.com/forums/topic/adding-custom-fields-search-to-wordpress-search/
That code looks good if it works :)
Thanks Tom. The code seems to be working just fine with the new GP, ACF and Gutenberg.
Your tech support is, as always, at super-hero level. Five gold stars for the whole GP team!
Best wishes
Denise
Great to hear! Thank you! :)
I've been hunting for a solution that will return search results within custom fields when the fields have been added by metabox.io. When I test with Adam's code, custom field data seems to be ignored. Data within custom fields gets ignored.
Hi Sunil,
I found this: https://stackoverflow.com/questions/36787391/add-acf-fields-to-search-results-page-wordpress
If that doesn't work, it would be good to reach out to ACF support as well.