一般WordPress默认删除文章时,文章上传到媒体库的图片等插件都不会自动删除,就是占用网站空间,那么WordPress如何删除文章同时删除缩略图及附件?今天就分享一下通过代码的方式来实现自动删除,可以不用手动去寻找查询,准确且效率高。

代码如下:

/* 删除文章时删除图片附件

/* ———————— */

function delete_post_and_attachments($post_ID) {

global $wpdb;

//删除特色图片

$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 );

}

//删除图片附件

$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\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\’);

使用方法

将上述代码放到WordPress主题 functions.php 文件中即可使用,其在删除文章时先执行函数内容,删除特色图片以及图片附件,如果在使用 action delete_post 而不是 before_delete_post 将导致删除文章后因媒体附件与文章关联已取消而无法正确删除。

相关新闻

发表评论

您的电子邮箱地址不会被公开。 必填项已用*标注

联系我们

联系我们

151-1101-0018

在线咨询:
邮件:30115776@qq.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信
关注微信
分享本页
返回顶部