I am an admin of a multi-author blog. I am implementing a monitoring system which will require me to downgrade a user from an ‘author’ (this role allows them to make a custom post) back to the ‘reader’ role if I think it is a spam account, or if they are breaking website rules.
After changing their role using the admin screen, how can I make all the posts they made delete automatically, without having to scroll and find them myself?
Many thanks
EDIT using advice from answers below:
add_action( 'set_user_role', 'wpse98904_remove_demoted_user_posts', 10, 2 );
function wpse98904_remove_demoted_user_posts( $demoted_author_id, $role ) {
// In here you'd search for all the posts by the user
$args = array(
'numberposts' => -1,
'author' => $demoted_author_id,
'post_type' => 'custom_post',
// So if your custom post type is named 'xyz_book', then use:
// 'post_type' => 'xyz_book',
);
$demoted_author_posts = get_posts( $args );
foreach( $demoted_author_posts as $p ) {
// delete the post (actually Trash it)
if($role == 'subscriber') {
wp_trash_post( $p->ID);
// To force the deletion (ie, bypass the Trash):
// wp_delete_post( $p->ID, true );
}
}
}
I used wp_trash_post to trash the events because adding ‘false’ to wp_delete_post did not work for me.
You can add actions to the
set_user_role
hook:Reference
set_user_role
hook — Codexset_user_role
hook in WP Tracwp_delete_post()
— CodexUsers roles are changed by the WP_User object firing the set_role() function. At the end of that function on line 815 of wp-includes/capabilities.php there is an action to hook to:
do_action( 'set_user_role', $this->ID, $role );
So, in your functions.php or in a plugin, you can grab that data as the hook fires after the user capability update, and delete all of a user’s posts with wp_delete_post.
Now, be careful, because as is, this snippet will permenently delete the post. If you want to just move it to trash, change the second parameter or wp_delete_post to false.