Use WP_User_Query
and the has_published_posts
parameter to limit results to users who have published the specified post type(s).
get_users()
is just a wrapper for WP_User_Query()
.
has_published_posts
(boolean / array) – Pass an array of post types
to filter results to users who have published posts in those post
types.true
is an alias for all public post types. Default is
null
.
Here’s a basic example of a User Query for users who have published a page post type:
// Set up arguments for query.
$args = [
'has_published_posts' => [ 'page' ],
'orderby' => 'post_count',
'order' => 'DESC',
];
// Create the WP_User_Query object
$user_query = new WP_User_Query( $args );
// Get results.
$users = $user_query->get_results();
// Check for results
if ( ! empty( $users ) ) {
echo '<ul>' . PHP_EOL;
// Loop through each author.
foreach ( $users as $user ) {
// Get all the user's data.
$user_info = get_userdata( $user->ID );
echo "\t" . '<li>' .
'<em>' . __( 'User ID: ', 'text-domain' ) . esc_html( $user->ID ) . '</em> ' .
esc_html( $user_info->first_name ) . ' ' .
esc_html( $user_info->last_name ) .
'</li>' . PHP_EOL;
}
echo '</ul>' . PHP_EOL;
} else {
echo __( 'No users found', 'text-domain' );
}