如何删除基于'user_meta'的所有用户和帖子?
问题描述:
我开发了一个小的wordpress应用程序,它有研究所(wp用户),培训师(wp用户),培训生(wp用户),课程(自定义文章)和通知(自定义文章)。所有的应用程序工作正常,但如果我删除一个机构的所有信息属于该机构像培训师,实习生,通知&课程也应该删除。当我创建“学院”用户时,我在wordpress表'wp_users'和'institute name'中存储所有相关信息,例如名字,姓氏在'wp_usermeta'中用'inistitute_name'作为'user meta'像下表是我的代码:如何删除基于'user_meta'的所有用户和帖子?
$user_data = array(
'ID' => '',
'user_pass' => '',
'user_login' => $first_name,
'user_email' => $user_email,
'first_name' => $first_name,
'last_name' => $last_name,
'role' => 'admin'//get_option('default_option')
);
$random_password = wp_generate_password(8,false);
$user_id = wp_insert_user($user_data);
update_user_meta($user_id, 'inistitute_name',$insititute_name);
在创建教练(或)见习我的代码如下所示:
$user_data = array(
'ID' => '',
'user_pass' => '',
'user_login' => $first_name,
'user_email' => $trainer_email,
'first_name' => $first_name,
'last_name' => $last_name,
'role' => 'trainer'
);
$random_password = wp_generate_password(8,false);
$user_id = wp_insert_user($user_data);
update_user_meta($user_id, 'inistitute_name',$this->institute_name[0]);
wp_set_password($random_password, $user_id);
在创建课程,我的代码如下所示:
$user_ID = get_current_user_id();
$institute_name = get_user_meta($user_ID, 'inistitute_name', true);
$post = array(
'post_title' => $title,
'post_content' => $description,
'post_status' => 'publish',
'post_type' => "courses"
);
$id = wp_insert_post($post);
update_post_meta($id, 'inistitute_name', $institute_name);
假设让我们说,如果一个研究所的“abcd”被删除,那么与该研究所相关的所有信息(如“培训师”,“实习生”,“课程”&'通知')也应根据'user_meta'字段被删除。可以删除吗? (或)我做错了吗?谁能告诉我我做错了什么?
答
我得到了解决形式wordpress.stackexchange.com链接到这个问题是在这里
答
试试这个代码:
$user_args = array(
'meta_key' => 'inistitute_name',
'meta_value' => 'your_value', //<-- replace it by your user_meta value.
'meta_compare' => '=',
'orderby' => 'ID',
'number' => -1
);
// Custom query.
$user_query = new WP_User_Query($user_args);
// Get query results.
$users = $user_query->get_results();
//print_r($users);
// Check for users
if (!empty($users))
{
// Loop over users.
foreach ($users as $user)
{
$user_id = $user->ID;
// Get each user's data.
$user_info = get_userdata($user->ID);
$user_display_name = $user_info->display_name;
$args = array(
'numberposts' => -1,
'post_type' => 'any', //<-- you can Specific type by array('post', 'my_custom_post')
'author' => $user_id
);
// get all posts by this user: posts, pages, attachments, etc..
$user_posts = get_posts($args);
if (!empty($user_posts))
{
// delete all the user posts
foreach ($user_posts as $user_post)
{
wp_delete_post($user_post->ID, true);
}
}
wp_delete_user($user_id, $reassign);
}
}
else
{
//"no user found"
}
我没有测试此代码,形成了我的WP知识。
请注意在测试此代码之前请确保执行数据库备份。