pre_get_posts : only get posts by wp_usermeta value

I’ve added a meta field on my authors (company). How can I only display the posts written by authors with a specific company value (company1 or company2 for example)?

I would like to do that within the pre_get_posts filter.

Solutions Collecting From Web of "pre_get_posts : only get posts by wp_usermeta value"

The WP_Query Object does not support retrieving posts by author_meta so neither will the pre_get_posts hook. The next best thing would be to run a quick WP_User_Query and get all users by the specific author_meta then limit our query to only pull posts from those authors. Here’s what that would look like:

/**
 * Modify Queries 
 *
 * @param WP_Query Object $query
 */
function theme_pgp( $query ) {

    // If we're on admin side, return
    if( is_admin() ) {
        return;
    }

    // Only apply to main queries
    if( $query->is_main_query() ) {

        // Get all users with a Company field
        $users = new WP_User_Query( array(
            'meta_key'      => 'company',
            'meta_value'    => 'company1',
            'fields'        => 'ID',
        ) );
        $authors = $users->get_results();

        if( ! empty( $authors ) ) {
            $query->set( 'author__in', $authors );
        }
    }
}
add_action( 'pre_get_posts', 'theme_pgp' );