Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WP delete media array ID on deleting post

Tags:

php

wordpress

Someone have a sample snippet to delete media ID on deleting post?

i have upload metafield that contain array ID of media file attached to post and i wish to delete media files also on deleting post and avoid to have pending/useless media loaded.

thanks

like image 322
Fabio Avatar asked Dec 29 '25 09:12

Fabio


1 Answers

You would be using the delete_post hook, which fires right before a post gets deleted (so you still have access to it). Inside your function, which then fires, you'd fetch all attachments (or attachment IDs) and remove them using wp_delete_attachment.

add_action( 'delete_post', 'delete_attachments_with_posts', 10, 2 );
function delete_attachments_with_posts( $post_id, $post ) {
    if ( $post->post_type == 'post' ) {
        $attachments = get_posts( array(
            'post_type' => 'attachment',
            'posts_per_page' => -1,
            'post_status' => 'any',
            'post_parent' => $post_id
        ) );
        foreach ( $attachments as $attachment ) {
            wp_delete_attachment( $attachment->ID, true );
        }
    }
}

References: Hook Function

like image 88
volkerschulz Avatar answered Dec 31 '25 21:12

volkerschulz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!