Home › Forums › General Issues › Making customfields searchable? › Reply To: Making customfields searchable?
Hi,
I’ve been having a similar issue for a while now. I use the flexible content field to allow my clients to create columns within WordPress and other elements they may need.
I’ve been working on a solution for a while (I’m no PHP developer, so forgive me here), I’ve gotten close thanks to stumbling onto this post from the old support site http://goo.gl/flryRN
I’ve had to amended it a little for my needs & it isn’t perfect at all, but maybe we can get to a better solution together?
You will need to use Relevanssi, with this code added to your functions.php file…
// Get Relevanssi to display excerpts from your custom fields
add_filter('relevanssi_excerpt_content', 'excerpt_function', 10, 3); function excerpt_function($content, $post, $query) {
global $wpdb; $fields = $wpdb->get_col("SELECT DISTINCT(meta_key) FROM $wpdb->postmeta");
foreach($fields as $key => $field){ $field_value = get_post_meta($post->ID, $field, TRUE); $content .= ' ' . ( is_array($field_value) ? implode(' ', $field_value) : $field_value ); }
$content = preg_replace($wordlist, '', $content);
return $content; }
This works, but (and there is a but) it seems to display post revisions, so if you’re like me and use Latin as place holders for dummy content during the build process, it shows up in the results. Also, it seems to show the custom field IDs at times too, depending where your search term shows up in the order of the ACF field content.
I’ve not figured out a solution to the revisions yet, but to remove the IDs I’ve tweaked the code for this…
// Get Relevanssi to display excerpts from your custom fields
add_filter('relevanssi_excerpt_content', 'excerpt_function', 10, 3); function excerpt_function($content, $post, $query) {
global $wpdb; $fields = $wpdb->get_col("SELECT DISTINCT(meta_key) FROM $wpdb->postmeta");
foreach($fields as $key => $field){ $field_value = get_post_meta($post->ID, $field, TRUE); $content .= ' ' . ( is_array($field_value) ? implode(' ', $field_value) : $field_value ); }
// Remove random terms from showing in the search. These are related to the names of the ACF field names
$wordlist = array('acf_id_1', 'acf_id_2', 'acf_id_3', 'acf_id_4');
foreach ($wordlist as &$word) {
$word = '/\b' . preg_quote($word, '/') . '\b/';
}
$content = preg_replace($wordlist, '', $content);
// The excerpt ready with bits removed from it
return $content; }
Again, not ideal, but works of sorts.
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.