首页 > 解决方案 > 删除用户后运行的挂钩

问题描述

我有一个功能,可以在用户注册时将用户复制到所有子站点。

我通过这样做实现了这一点:

function sync_user( $user_id )
{
    $list_ids = get_sites();
    $current_site = get_current_site();

    $info = get_userdata($user_id);



    foreach( $list_ids as $list )
    {

        if ( $list->blog_id != $current_site->id )
        {
            add_user_to_blog($list->id, $info->ID, 'subscriber');
        }

    }

    // quick fix for: above somehow doesn't add to main site. add to main site here.
    add_user_to_blog(1, $info->ID, 'subscriber');

}

现在,当我从站点中删除用户时,我想“取消同步”用户。我试图通过使用'remove_user_from_blog'来挂钩它,但它导致了无限循环。

我在哪里可以挂钩以下代码,以便我可以删除之前使用上述代码添加的所有用户?

function unsync_user( $user_id )
{
    $list_ids = get_sites();

    foreach( $list_ids as $list )
    {
        remove_user_from_blog( $user_id, $list->ID );
    }
}

为了清楚起见,编辑了标题

标签: wordpressmultisite

解决方案


AbdulRahman 在这点上是正确的。当用户从用户列表中单击“删除”时,该操作不会触发“delete_user”或“deleted_user”挂钩。我测试了它。

我认为这很棘手。所以,这里是如何添加自定义的 removed_user 操作。将以下这些行添加到您的插件中。

add_action('remove_user_from_blog', function($user_id, $blog_id) {
    // checking current action
    // refer: wp-admin/users.php:99
    $wp_list_table = _get_list_table( 'WP_Users_List_Table' );

    if( $wp_list_table->current_action() != 'doremove' ) {
        return; // only proceed for specific user list action
    }

    $fire_removed_user_hook = null; // closure reference

    $fire_removed_user_hook = function() use ($user_id, $blog_id, &$fire_removed_user_hook) {
        do_action( 'removed_user', $user_id, $blog_id );

        // remove the hook back
        remove_action('switch_blog', $fire_removed_user_hook);
    };

    // restore_current_blog called at the last line in the remove_user_from_blog function
    // so action switch_blog fired
    add_action('switch_blog', $fire_removed_user_hook);
}, 10, 2);


add_action('removed_user', function($user_id, $blog_id) {
 // the user removed from be blog at this point
}, 10, 2);

推荐阅读