2
votes

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".

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

4

4 Answers

2
votes

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);
    }
}
0
votes

You could use add_action hook into delete_post function, and run a function that will deelte the featred image after getting it by the post id. https://codex.wordpress.org/Plugin_API/Action_Reference/delete_post

0
votes

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.

-1
votes

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
}