如何在我的插件中添加admin_init,以便贡献者可以上传图像

时间:2013-02-06 07:55:19

标签: wordpress-plugin wordpress

我有一个名为MyPlugin的插件由我编写。我有一个是或否单选按钮,如果选项是肯定意味着它应该允许贡献者上传图像而不意味着它不应该允许。

这是允许贡献者上传图片的代码

if ( current_user_can('contributor') && !current_user_can('upload_files') )
    add_action('admin_init', 'allow_contributor_uploads');
function allow_contributor_uploads() {
    $contributor = get_role('contributor');
    $contributor->add_cap('upload_files');
} 
// this is the code to remove if the capabilities if it is added

if ( current_user_can('contributor') && current_user_can('upload_files') )
    add_action('admin_init', 'remove_contributor_upload');
function remove_contributor_upload(){
    $con = get_role('contributor');
    $con->remove_cap('upload_files');
} 

我需要一个帮助,我应该把这个代码放在插件中,我尝试了但是我得到了错误

Error in wp-includes/capabilities.php on line 1059

1 个答案:

答案 0 :(得分:1)

你正在调用init()之前无法调用的函数,所以它们是未定义的(具体来说,wp_get_current_user()在wp-includes / pluggable.php中定义,直到所有插件都被加载后才会加载加载)。您需要重新安排代码以在调用admin_init后检查用户权限,例如

add_action('admin_init', 'allow_contributor_uploads');
function allow_contributor_uploads() {
    if ( current_user_can('contributor') && !current_user_can('upload_files') ) {
        $contributor = get_role('contributor');
        $contributor->add_cap('upload_files');
    }
}
// this is the code to remove if the capabilities if it is added

add_action('admin_init', 'remove_contributor_upload');
function remove_contributor_upload(){
    if ( current_user_can('contributor') && current_user_can('upload_files') ) {
        $con = get_role('contributor');
        $con->remove_cap('upload_files');
    }
}

注意:这里只是解决你的错误问题,没看过你正在做的事情的逻辑!