I have looked at many posts and questions regarding searches for custom meta, but I want to search for posts and include those if the search query matches an author name.
I have come up with the following code but it is not working. For some reason, it returns posts with status "revision"
First, I hooked my three functions to their respective hooks:
add_filter('posts_join', 'custom_posts_join' );
add_filter('posts_groupby', 'custom_posts_groupby' );
add_filter('posts_where', 'custom_posts_where' );
Then, I proceed with each function:
custom_posts_join
function custom_posts_join($join){
global $wpdb;
if( is_search() && !is_admin()) {
$join .= " LEFT JOIN $wpdb->postmeta ON $wpdb->posts.ID = $wpdb->postmeta.post_id ";
}
return $join;
}
custom_posts_groupby
function custom_posts_groupby( $groupby ) {
global $wpdb;
if( is_search() && !is_admin()) {
$groupby = "$wpdb->posts.ID";
}
return $groupby;
}
custom_posts_where
function custom_posts_where( $where = '' ){
if ( is_search() && !is_admin()) {
global $wpdb;
$search = ( isset($_GET["s"]) ) ? sanitize_text_field($_GET["s"]) : false ;
$search = (string)$search;
$users = $wpdb->get_results( "SELECT user_id FROM $wpdb->usermeta WHERE meta_key = 'first_name' AND meta_value = '$search'",OBJECT_K );
foreach ($users as $user)
{
$users_ids.=$user->user_id.',';
}
$users_ids = rtrim($users_ids, ',');
$where .= " AND ( ($wpdb->posts.post_author IN ({$users_ids}))
OR ($wpdb->posts.post_title LIKE '$search')
OR ($wpdb->posts.post_content LIKE '$search') )
AND $wpdb->posts.post_type = 'post'
AND $wpdb->posts.post_status = 'publish'";
}
return $where;
}