WP Search Form Query: Add Author's posts into search query
As the title suggests, I'm looking for WordPress advice relative to leveraging the standard searchform.php
functionality to additionally query the author
field when performing searches. I've tried various different means to do this without any success, and so I'm coming to quite the headache. Below are the template files used:
searchform.php
?php
/**
* Template for displaying search forms in Twenty Seventeen
*
* @package WordPress
* @subpackage Twenty_Seventeen
* @since 1.0
* @version 1.0
*/
?
?php $unique_id = esc_attr( uniqid( 'search-form-' ) ); ?
div class=global-search
form role=search method=get class=search-form action=?php echo esc_url( home_url( '/' ) ); ?
label for=?php echo $unique_id; ?
span class=screen-reader-text sr-only?php echo _x( 'Search for:', 'label', 'sdwp' ); ?/span
/label
input type=search id=?php echo $unique_id; ? class=search-field value=?php echo get_search_query(); ? name=s /
button type=submit class=search-btni class=fas fa-search/ispan class=screen-reader-text sr-only?php echo _x( 'Search', 'submit button', 'sdwp' ); ?/span/button
/form
/div
functions.php
- the bit of code I've written up after much reiteration
function add_author_to_query( $query ) {
//do not run on admin side
if( is_admin() ) return;
if ( $query-is_main_query() $query-is_search() ) {
$submitted_data = get_search_query();
// Get all users who may match the submitted data
$users = new WP_User_Query( array(
'search' = $submitted_data,
'search_columns' = array( 'user_login', 'user_nicename')
) );
$authors = $users-get_results();
foreach($authors as $author) {
$author_ids[] = $author-ID;
}
if( ! empty( $authors ) ) {
$query-set('post_type', array( 'post', 'article', 'page', 'bio', 'author', 'article_type'));
$query-set( 'author__in', $author_ids );
// $query-set( 'author__in', $authors );
}
}
add_action( 'pre_get_posts', 'add_author_to_query' );
Topic query customization Wordpress search
Category Web