Extending the site search to include a single custom field

I managed to resolve by extending the query

function extend_search( $search, &$wp_query ) {
    global $wpdb;

    if ( empty( $search ))
        return $search;

    $terms = $wp_query->query_vars[ 's' ];
    $exploded = explode( ' ', $terms );
    if( $exploded === FALSE || count( $exploded ) == 0 )
        $exploded = array( 0 => $terms );

    $search="";
    foreach( $exploded as $tag ) {
        $search .= " AND (
            ($wpdb->posts.post_title LIKE '%$tag%')
            OR ($wpdb->posts.post_excerpt LIKE '%$tag%')
            OR EXISTS
            (
                SELECT * FROM $wpdb->postmeta
                WHERE post_ID = pl_posts.ID
                    AND meta_key = '--KEY--'
                    AND meta_value LIKE '%$tag%'
            )

        )";
    }

    return $search;
}

Leave a Comment