Search code examples
wordpresswordpress-rest-api

Wordpress rest api return users who have not created a post


Using the wordpress rest api, is there a way to return all users, regardless of whether they have created a post or not. I am aware that I can do that if authenticated as an admin user, but I need to be able to do it as a standard user (subscriber)


Solution

  • You can do so by adding this filter in your functions.php file.

    add_filter( 'rest_user_query', 'prefix_remove_has_published_posts_from_wp_api_user_query', 10, 2 );
    /**
     * Removes `has_published_posts` from the query args so even users who have not
     * published content are returned by the request.
     *
     * @see https://developer.wordpress.org/reference/classes/wp_user_query/
     *
     * @param array           $prepared_args Array of arguments for WP_User_Query.
     * @param WP_REST_Request $request       The current request.
     *
     * @return array
     */
    function prefix_remove_has_published_posts_from_wp_api_user_query( $prepared_args, $request ) {
        unset( $prepared_args['has_published_posts'] );
    
        return $prepared_args;
    }
    

    Source: WP Users Endpoint doesn't return all users