wordpress - 删除用户后运行的挂钩
问题描述
我有一个功能,可以在用户注册时将用户复制到所有子站点。
我通过这样做实现了这一点:
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 );
}
}
为了清楚起见,编辑了标题
解决方案
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);
推荐阅读
- angular - 如何只查询一次 Firestore DB?我想避免当文档发生更改时,snapshotChanges() 会发出新值
- javascript - 将字段重置为默认值,无需表单
- ios - GameController -[_GCControllerManager setupHIDMonitor:] 在 iOS 14 中崩溃
- html - 如何根据角度 10 的高度和宽度禁用文本区域中的更多输入?
- reactjs - 我正在尝试将多个文件打包到一个数组中,但一次只显示一个
- excel - 基于序列的函数,用于替换另一个工作表中的序列
- python - 使用 beautifulsoup 抓取链接页面
- c++ - 我应该总是在 __builtin_return_address 之后使用 __builtin_extract_return_addr
- c# - LINQ except() 的意外行为
- latex - 使用 Pandoc 文本到单词