WordPress Search on Custom Fields

Home/WordPress Search on Custom Fields

The WordPress default search has never been the most powerful tool in the WordPress arsenal, and hasn’t changed much over the years. Developer and focus group discussions have promised much, but it’s still the same old basic search functionality that existed way back when.

However, it’s possible to extend the search to include any custom fields you may have set up with the addition of a few lines of code. Add the following code to your functions.php file in your theme or child theme folder, and you should be able to search both the front end and admin panel via your custom fields, with the minimum of fuss.

function custom_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', 'custom_search_join' );


function custom_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', 'custom_search_where' );


function custom_search_distinct( $where ) {
    global $wpdb;

    if ( is_search() ) {
        return "DISTINCT";
    }

    return $where;
}
add_filter( 'posts_distinct', 'custom_search_distinct' );
2017-07-10T16:37:52+00:00 July 10th, 2017|WordPress Snippets|0 Comments

About the Author:

Warren Chandler is a freelance web programmer and web developer, based in Frinton on Sea, Essex. Warren specialises in web programming, web design, corporate identity, copy writing, SEO, logo and print media for home, work, and mobile platforms.

Leave A Comment