Delete featured image with post WordPress

Iv’e been searching for a while now and my search so far has been very unsuccessful. I’m looking for a function that deletes the featured image and post when clicking delete post on the posts page in the dashboard.

What I would like: Clicking delete on a post deletes instantly along with it’s featured image instead of being moved to the “trash”.

Read More

Sorry I’m not a pro developer, I’m a noob and just starting out. Any help would be great. Thank you!

Related posts

Leave a Reply

4 comments

  1. In any case, wp_delete_attachment requires attachment_id and not post_id. saved you half an hour 😉

    add_action( 'wp_trash_post', 'delete_post_permanently' );
    
    function delete_post_permanently( $post_id ){    
        wp_delete_post($post_id, true); // deletes post
        //wp_delete_attachment ( $post_id, true ); // deletes attachment
        if( has_post_thumbnail( $post_id ) )
        {
            $attachment_id = get_post_thumbnail_id( $post_id );
            wp_delete_attachment($attachment_id, true);
        }
    }
    
  2. You can attach the WordPress function for “before deleting a post”…

    So under your theme’s function.php file:

    function delete_associated_media($id) {
    // check if page
    if ('page' !== get_post_type($id)) return;
    
    $media = get_children(array(
        'post_parent' => $id,
        'post_type' => 'attachment'
    ));
    if (empty($media)) return;
    
    foreach ($media as $file) {
        // pick what you want to do
        wp_delete_attachment($file->ID);
        unlink(get_attached_file($file->ID));
    }
    }
    add_action('before_delete_post', 'delete_associated_media');
    

    This will delete all the attachments (images) on that page being removed. You will have to tweak it just to be the featured image instead, however it might help you figure it out.

  3. You can use wp_trash_post action hook, it runs onn post, page, or custom post type is about to be trashed

    add_action( 'wp_trash_post', 'delete_post_permanently' );
    
    function delete_post_permanently( $post_id ){    
        wp_delete_post($post_id, true); // deletes post
        wp_delete_attachment ( $post_id, true ); // deletes attachment
    }