How to filter search by users in WordPress

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.

Share this post

You might also like...

Best WordPress hosting
Articles & How-to

Best WordPress hosting

WordPress hosting is becoming increasingly popular as a reliable and affordable way to host websites. The best WordPress hosting providers offer powerful features, reliable uptime,

Read More »

Comment

Your email address will not be published. Required fields are marked *