4

我想在编辑帖子页面上的作者选择下拉列表中更改自定义帖子类型的用户列表。我可以使用过滤器挂钩吗?我还没有找到任何关于过滤钩子的信息,它可以满足我的需求。

钩子应该(理论上)让我返回一个用户数组,这些用户将填充底部的选择框。我想这样做的原因是,我可以根据用户的角色有条件地过滤掉不同帖子类型的用户。作为管理员(或其他管理员),我不想在将用户设为作者之前检查用户是否具有特定角色。

代码示例:

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;
}
4

1 回答 1

4

您可以使用挂钩“wp_dropdown_users_args”。

在主题的 functions.php 文件中添加以下代码片段。

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;
}

让我知道这是否适合您。

于 2017-02-02T11:52:27.677 回答