Using the action hook delete_user
is the right way to do it, but there are a couple of things missing. The main one being that you haven’t set up any $args
for the WP_Query
that fetches the custom post type entries with the user-id metakey of the deleted user.
add_action( 'delete_user', 'delete_his_posts');
function delete_his_posts($user_id) {
$args = array(
'post_type' => 'your_custom_post_type', // Replace with the name of your custom post type
'meta_query' => array(
array(
'key' => 'user-id', // Your metakey
'value' => $user_id,
'compare' => '='
)
),
'posts_per_page' => -1
);
$the_query = new WP_Query($args);
if ($the_query->have_posts()) {
while ($the_query->have_posts()) {
$the_query->the_post();
wp_delete_post(get_the_ID(), false); // Soft delete. If you want hard delete, change false to true
}
wp_reset_postdata(); // Important! Resets the post data after our custom query
}
}