Toggle User Roles with button

时间:2015-02-19 作者:Andrew Lazarus

我不知道这是否可行,但我有两个用户角色:HeroLegend. 当人们订阅我的网站时,他们会被分配Hero 用户角色。

我希望能够将用户切换到Legend 通过打开按钮的用户角色/users.php 在其自己的列中

是否有可以在两个角色之间交换用户角色的功能?或者这是不能在飞行中完成的事情?

我知道你可以在表格顶部“更改用户角色”,但对于网站的其他管理员,我希望能够有一个按钮,让他们感觉自己已经更改了它。

注意:Legend\'我们可以看到比Hero 用户

1 个回复
最合适的回答,由SO网友:David Gard 整理而成

碰巧,我的一个网站上有一个非常类似的东西,允许管理员更新一些自定义用户元。

基本上,您需要添加一个额外的列,然后用一个链接填充它,以完成您想要的操作。当您单击链接时,一些jQuery会触发AJAX请求以更新用户角色,然后您会被重定向回/wp-admin/users.php

这里的主要工作是wp_update_user() function, 我鼓励你看看。

首先,将此添加到functions.php 文件以添加附加列及其内容。这还将添加AJAX函数,当调用它时,它将真正发挥所有的作用-

/** Manage custom columns on instances of \'WP_List_Table\' */
add_action(\'init\', \'my_setup_custom_columns\', 110, 0);
function my_setup_custom_columns(){
    
    /** Manage columns on the WP_Users_List_Table */
    add_filter(\'manage_users_columns\', \'my_add_custom_columns\');
    
    /** Populate additional columns on the WP_Users_List_Table */
    add_action(\'manage_users_custom_column\', \'my_fill_custom_columns_return\', 10, 3);
    
}

/**
 * Add additional custom columns to the list table views in the admin area
 *
 * @param required array $columns   The columns that currently exist
 */
function my_add_custom_columns($columns){

    /** Grab the page that is currently being viewed */
    global $pagenow;
    
    /** Users specific columns (http://www.blog.com/wp-admin/users.php) */
    if($pagenow === \'users.php\') :
    
        $new_columns[\'my-change-user-role\'] = __(\'Change Role\');
        
    endif;
    
    $columns = $columns + $new_columns;
    
    return $columns;
    
}

/**
 * Fill the custom columns by returning data
 *
 * @param required string $column_value The current column value (in this case \'null\' since the columns are new)
 * @param required string $column_name  The name of the column to return data for
 * @param required integer $object_id   The ID of the curent object to fill the column for
 * @return string $column_value         The value to fill the column with
 */
function my_fill_custom_columns_return($column_value, $column_name, $object_id){

    switch($column_name) :
    
        /**
         * ID (the ID of the current object)
         */
        case \'my-change-user-role\' :
        
            $user = get_userdata($object_id);
            $role = $user->roles[0];
            
            if($role === \'legend\') :
                $column_value = \'<span user-id="\' . $object_id . \'" new-role="subscriber" class="change-user-role">Downgrade to a Hero</span>\';
            elseif($role === \'hero\') :
                $column_value = \'<span user-id="\' . $object_id . \'" new-role="document_administrator" class="change-user-role">Upgrade to a Legend</span>\';
            else:
                $column_value = \'&#8212;\';
            endif;
            
            break;
    
    endswitch;
    
    return $column_value;
    
}

/**
 * Change the role of a given user
 */
add_action(\'wp_ajax_change_user_role\', \'my_update_user_role\');
function my_update_user_role(){

    /** Update the user role */
    $args = array(
        \'ID\'    => $_POST[\'user_id\'],
        \'role\'  => $_POST[\'new_role\']
    );
    $result = wp_update_user($args);
    
    /** Check whether or not the update was successful */
    if(is_wp_error($user_id)) :
        $message = \'An unexpected error occured, please try again.\';
        $url = false;
    else :
        $message = \'success\';
        $url = admin_url(\'users.php\');
    endif;
    
    $return = array(
        \'message\'   => $message,
        \'url\'       => $url
    );
    echo json_encode((object)$return);
    
    wp_die(); // This is required to terminate immediately and return a proper response
    
}
接下来,将其添加到查看管理区域时可以访问的样式表中-

.wp-list-table.users .manage-column.column-my-change-user-role{
    width:  150px;
}
.wp-list-table.users span.change-user-role{
    color:  #0074A2;
    cursor: pointer;
}
.wp-list-table.users span.change-user-role:hover{
    color:  #2EA2CC;
}
最后,将此添加到查看管理区域时可以访问的JS文件中-

jQuery(function($){
    
    $(document).ready(function(){
        updateUser.init();
    });
    
    var updateUser = {
    
        /**
         * Psuedo constructor
         */
        init : function(){
        
            this.userChangeRoleButtons = $(\'.wp-list-table.users span.change-user-role\');   // Grab all instance of the buttons to change the user role
            this.createEvents();                                                            // Create the events to be handled by this object
            
        }, // init
        
        /**
         * Create the events that are to be handled by this object
         */
        createEvents : function(){
        
            var t = this;   // This object
            
            /**
             * Handle clicks of the change user role buttons
             */
            this.userChangeRoleButtons.on(\'click\', function(e){
            
                t.changeRole($(this));
                
            });
            
        }, // createEvents
        
        /**
         * Updates the user role as required
         */
        changeRole : function(clicked){
        
            var t               = this, // This object
                user_id         = clicked.attr(\'user-id\'),
                new_role        = clicked.attr(\'new-role\');
            
            var data = {    // The data object to pass to the AJAX request
                action:     \'change_user_role\',
                user_id:    user_id,
                new_role:   new_role
            };
            
            /** Make the AJAX request to update the download count */
            var action_jqxhr = $.post(ajaxurl, data, function(response){
            
                /** Parse the JSON response */
                var obj = JSON.parse(response);
                
                /** Ensure that there were no errors and update the \'Change role\' button text */
                if(obj.message.indexOf(\'error\') === -1){    // There was no error, redirect the user back to this page
                
                    top.location.replace(obj.url);
                    
                } else {    // There was an error, tell the user about it
                
                    alert(obj.message); // Show the error to the user
                    
                }
                
            }).fail(function(){ // There was an AJAX error...
                alert(\'An unexpected error occured, please try again.\');
            });
            
        } // changeRole
        
    };
    
});

结束

相关推荐

jquery issue in functions.php

我正在处理的主题中有一个问题,我不知道如何解决它。该主题有几个jquery脚本,需要加载到头部才能工作。如果没有所有这些,主题就失败了。这是我打电话给的人jquery-1.8.2。最小jsjquery-1.6.1。min.jsjquery。放松。1.3。jsjquery-ui-1.8.11。风俗min.jsjquery-ui-1.8.21。风俗最小js现在使用WordPress,我想您可以将jquery排队,然后加载所有版本。我的问题是,当我尝试这样做并删除上面的脚本时,一切都失败了。我将所有脚本放入函数