To filter the search results in WordPress by user, you can use the pre_get_posts
action in your theme’s functions.php file.
Here’s an example of how you can use the pre_get_posts
action to filter the search results by user:
// Filter search by users
// More snippets at wpunplugged.com
function my_custom_search_filter( $query ) {
if ( ! is_admin() && $query->is_main_query() && $query->is_search() ) {
$query->set( 'author', '1' );
}
}
add_action( 'pre_get_posts', 'my_custom_search_filter' );
This code will filter the search results to only include posts authored by user with an ID of 1. You can customize the filter by modifying the value of the author
parameter. For example, you can use a different user ID or use a comma-separated list of user IDs to include posts from multiple users.
Note that this code will only filter the search results on the front end of your WordPress site. If you want to filter the search results in the WordPress admin area as well, you can use the pre_get_posts
action in a separate function and hook it to the admin_init
action.