WP 在删除帖子时删除媒体阵列 ID

问题描述 投票:0回答:1

有人有一个在删除帖子时删除媒体 ID 的示例片段吗?

我已上传元字段,其中包含附加到帖子的媒体文件的数组 ID,我希望在删除帖子时也删除媒体文件,并避免加载待处理/无用的媒体。

谢谢

php wordpress
1个回答
0
投票

您将使用

delete_post
钩子,它会在帖子被删除之前触发(因此您仍然可以访问它)。在随后触发的函数内,您将获取所有附件(或附件 ID)并使用
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 );
        }
    }
}

参考文献:钩子函数

© www.soinside.com 2019 - 2024. All rights reserved.