skip to Main Content

I would like to know if just using wp_delete_post($post_id, true); is enough to delete everything in DB that is tied to the post, skipping the trash.

According to the documentation it is, but there are several answers on the internet mentioning to use delete_post_meta also, like this:

// Delete all Post Meta
foreach (get_post_meta($post_id) as $key => $val)  {
    delete_post_meta($post_id, $key);
}

wp_delete_post($post_id, true);

What’s the best practice?

2

Answers


  1. YES. Using wp_delete_post($post_id, true) deletes all post-related information from the database, including attachments and post meta data, and bypasses the trash, resulting in immediate deletion. But, if you want to delete post meta data associated with the post, you should use delete_post_meta() function in addition to wp_delete_post() function.

    Login or Signup to reply.
  2. According to the source on the page you linked, wp_delete_post($post_id, true); deletes all the metadata and comments linked to the post. It force deletes the post and does therefore bypass the trash. As an answer to your question, it is enough.

    Reference in code (wp-includes/post.php:3438-3448):

    $comment_ids = $wpdb->get_col( $wpdb->prepare( "SELECT comment_ID FROM $wpdb->comments WHERE comment_post_ID = %d ORDER BY comment_ID DESC", $postid ) );
    foreach ( $comment_ids as $comment_id ) {
        wp_delete_comment( $comment_id, true );
    }
    
    wp_defer_comment_counting( false );
    
    $post_meta_ids = $wpdb->get_col( $wpdb->prepare( "SELECT meta_id FROM $wpdb->postmeta WHERE post_id = %d ", $postid ) );
    foreach ( $post_meta_ids as $mid ) {
        delete_metadata_by_mid( 'post', $mid );
    }
    

    If you would only want to delete post meta, please refrain of using wp_delete_post() and do instead use delete_post_meta().

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search