phpwordpresscustom-post-typewordpress-hook

WordPress Filter for changing author list in edit post Authors box


I want to change the list of users in the Author select dropdown on the edit post page for a custom post type. Is there a filter hook I can use for this? I haven't been able to find any information on a filter hook that does what I want.

The hook should (in theory) let me return a user array and those will be the users that populate the select box at the bottom. The reason I want to do this is so I can conditionally filter out users by their role for different post types. As an admin (or other admins) I don't want to have to check if user has certain role before making them the author.

Example of code:

add_filter('example_filter', 'my_custom_function');
function my_custom_function ( $users ){

    // Get users with role 'my_role' for post type 'my_post_type'
    if( 'my_post_type' == get_post_type() ){
        $users = get_users( ['role' => 'my_role'] );
    }

    // Get users with role 'other_role' for post type 'other_post_type'
    if( 'other_post_type' == get_post_type() ){
        $users = get_users( ['role' => 'other_role'] );
    }

    return $users;
}

Solution

  • You can use hook 'wp_dropdown_users_args'.

    Add below code snippet in your theme's functions.php file.

    add_filter( 'wp_dropdown_users_args', 'change_user_dropdown', 10, 2 );
    
    function change_user_dropdown( $query_args, $r ){
        // get screen object
        $screen = get_current_screen();
    
        // list users whose role is e.g. 'Editor' for 'post' post type
        if( $screen->post_type == 'post' ):
            $query_args['role'] = array('Editor');
    
            // unset default role 
            unset( $query_args['who'] );
        endif;
    
        // list users whose role is e.g. 'Administrator' for 'page' post type
        if( $screen->post_type == 'page' ):
            $query_args['role'] = array('Administrator');
    
            // unset default role 
            unset( $query_args['who'] );
        endif;
    
        return $query_args;
    }
    

    Let me know if this works for you or not.