skip to Main Content

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

2

Answers


  1. Chosen as BEST ANSWER

    i'd solved

    add_action( 'before_delete_post', 'wps_remove_attachment_with_post', 10 );
    function wps_remove_attachment_with_post( $post_id ) {
    
    global $post;
    $post_type = get_post_type( $post_id );
        if ( $post_type == '<post_type_slug>') {
            
            $gallery = array();
            $meta = get_post_meta( $post_id, '<cpt_metafield>', true );
            $gallery = explode( ',', $meta );
            
            foreach ( $gallery as $img_id ) {
                echo wp_get_attachment_image( $img_id );
                wp_delete_attachment( $img_id, true );
            }
       }
    }
    

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

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