i have some Custom post type with "user-id" metakey how can i delete all row in table on deleting user request? the user is not author of post, he have only metakey (user_id) stored inside table.

i can provide user capability to delete the post but need php code to perform delete whole row with user_id .


for ex.

add_action( 'delete_user', 'delete_his_posts');

function delete_his_posts($user_id) {
$user = get_user_by('id', $user_id);
$the_query = new WP_Query( $args );
    if ( have_posts() ) {
        while ( have_posts() ) { 
            wp_delete_post( $post->ID, false ); 


  • Where's the $args array defined?
    – Abhik
    Commented Oct 20, 2023 at 12:47

1 Answer 1


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(
                '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()) {
            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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.