I’ve currently got a Custom Post Type with 2 part titles; I’ve got everything working perfectly on the front end. But when it comes to searching for a post, the post you’re searching for doesn’t always show up because part of the title is in the meta for that post.
Is there any way that I can include the meta in the back end search for the Custom Post Type?
Untested, but the following should work:
add_action( 'posts_clauses', 'wpse110779_filter_admin_search', 10, 2 );
function wpse110779_filter_admin_search( $pieces, $query ){
global $wpdb;
//Check if this is the main query,and is a search on the admin screen
if( $query->is_search() & $query->is_admin() && $query->is_main_query() ){
//Collect post types & search term
$post_types = $query->get('post_type');
$search = $query->get('s');
//Check if query is for 'my-cpt' post type
if( 'my-cpt' == $post_types
|| ( is_array( $post_types ) && in_array( 'my-cpt', $post_types ) )
){
//Set up meta query
$meta_query = array( array(
'key' => 'my_key',
'value' => $search,
'compare' => 'LIKE'
));
//Generate sql
$meta_sql = get_meta_sql( $meta_query, 'post', $wpdb->posts, 'ID', $query );
$pieces['join'] . = " ". $meta_sql['join'];
$pieces['where'] . = " OR (" . $meta_sql['where'] .")";
}
}
return $pieces;
}
Please note this completely untested, but should work in principle, and will atleast get you started.