当前位置:首页原创文章WordPress删除文章同时删除文章中的图片和附件

WordPress删除文章同时删除文章中的图片和附件

只需将下面的 PHP 代码加入到主题目录下的 functions.php 文件底部就可以了。

在主题的functions.php或子主题的functions.php文件中最下方加入代码:

//删除文章时删除图片附件,极主题jitheme.com
function delete_post_and_attachments($post_ID) {
    global $wpdb;
    //删除特色图片,极主题jitheme.com
    $thumbnails = $wpdb->get_results( "SELECT * FROM $wpdb->postmeta WHERE meta_key = '_thumbnail_id' AND post_id = $post_ID" );
    foreach ( $thumbnails as $thumbnail ) {
        wp_delete_attachment( $thumbnail->meta_value, true );
    }
    //删除图片附件,极主题jitheme.com
    $attachments = $wpdb->get_results( "SELECT * FROM $wpdb->posts WHERE post_parent = $post_ID AND post_type = 'attachment'" );
    foreach ( $attachments as $attachment ) {
        wp_delete_attachment( $attachment->ID, true );
    }
    $wpdb->query( "DELETE FROM $wpdb->postmeta WHERE meta_key = '_thumbnail_id' AND post_id = $post_ID" );
}
add_action('before_delete_post', 'delete_post_and_attachments');

给TA打赏
共{{data.count}}人
人已打赏
B2美化原创文章

如何将原生主题日期更改为*月*日

2022-9-7 22:27:28

原创文章

WordPress SVG文件上传如何实现,让WP支持SVG文件上传

2022-9-29 10:23:52

0 条回复 A文章作者 M管理员
    暂无讨论,说说你的看法吧
购物车
优惠劵
有新私信 私信列表
搜索