Skip to content

Instantly share code, notes, and snippets.

@imvaskii
Created July 5, 2017 05:18
Show Gist options
  • Save imvaskii/dfdf7ba90e0518dede977977150dc240 to your computer and use it in GitHub Desktop.
Save imvaskii/dfdf7ba90e0518dede977977150dc240 to your computer and use it in GitHub Desktop.
WordPress search functionality to include authors' posts in search result if the search keyword matches authors' name.
<?php
if ( ! function_exists( 'cre_custom_search_query' ) ) {
/**
* Creates custom search query
* @param WP_Query object
* @return posts object
*/
add_action( 'pre_get_posts', 'cre_custom_search_query', 100 );
function cre_custom_search_query( $query ) {
if ( is_search() ) {
// Order by post id desc
$query->set('orderby', 'post_date');
$query->set('order', 'DESC');
$authors = cre_authors_by_keyword( $query->get('s') );
// include posts by author.
if ( ! empty( $authors ) ) {
$query->set('s', '');
$query->set( 'author__in', $authors );
}
}
}
}
if ( ! function_exists( 'cre_authors_by_keyword' ) ) {
/**
* Returns authors/users user ids by searching against their usernames,
* matching provided keyword.
*
* @param string $keyword
* @return mixed|array
*/
function cre_authors_by_keyword( $keyword ) {
if ( empty( $keyword ) ) {
return null;
}
$keyword_ = explode( ' ', $keyword );
$first_name = $keyword_[0] ? $keyword_[0] : false;
$last_name = $keyword_[1] ? $keyword_[1] : false;
$authors = new WP_User_Query(
[
'has_published_posts' => true,
'search_columns' => ['display_name', 'user_login', 'user_nicename', 'user_email'],
'fields' => ['ID'],
'who' => 'authors',
'order' => 'ASC',
'orderby' => 'display_name',
'search' => '*'.esc_attr( strtolower( str_replace( ' ', '', $keyword ) ) ).'*',
'number' => 10,
'meta_query' => [
'relation' => 'AND',
[
'relation' => 'OR',
[
'key' => 'first_name',
'value' => $first_name,
'compare' => 'LIKE'
],
[
'key' => 'last_name',
'value' => $last_name,
'compare' => 'LIKE'
],
[
'key' => 'description',
'value' => $keyword ,
'compare' => 'LIKE'
]
],
// https://codex.wordpress.org/Roles_and_Capabilities#User_Level_to_Role_Conversion
[
'relation' => 'AND',
[
'key' => 'wp_user_level',
'value' => [ 2, 3, 4, 5, 6, 7 ],
'compare' => 'IN',
]
]
]
]
);
// var_dump( $authors ); die;
if ( $authors->get_total() > 0 ) {
return wp_list_pluck( $authors->get_results(), 'ID' );
}
return null;
}
/**
* Adds functionality to include `display_name` column to be included in search clolumn for WP_User_Query
*
* @return array
*/
add_filter( 'user_search_columns', function( $search_columns ) {
$search_columns[] = 'display_name';
return $search_columns;
} );
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment