Add your meta Fields to the WordPress Default Search

Short Answer
Do you want your meta fields text to show up on your search results with Wordpress default search? then you have to add some php to your functions.php. See the snippet below:

after a few months of working with cpts and meta fields I realized that all the text that are in meta fields will not show up on search results with Wordpress’ default search bar. I searched online and found a simple fix for this:

You need to add the following snippet to your functions.php (or with a snippet plugin) :

<?php /** * Extend WordPress search to include custom fields * * https://adambalee.com */ /** * 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 $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_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’ );

Make sure you either have a child theme installed when modifying the functions.php, otherwise I suggest you use this plugin: https://wordpress.org/plugins/code-snippets/

 

This code was found on: https://adambalee.com/search-wordpress-by-custom-fields-without-a-plugin/ .. he explaines perfectly what each piece of the code does… so big thanks to Adam!

 

 

it_ITItalian
en_USEnglish it_ITItalian

Questo sito fa uso di cookie per migliorare l’esperienza di navigazione degli utenti. Può conoscere i dettagli consultando la nostra privacy policy qui. Proseguendo nella navigazione si accetta l’uso dei cookie; in caso contrario è possibile abbandonare il sito.