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');
将上述代码放到主题functions.php文件中即可使用,其在删除文章时先执行函数内容,删除特色图片以及图片附件,如果在使用action delete_post而不是before_delete_post将导致删除文章后因媒体附件与文章关联已取消而无法正确删除。
上一个:民勤网站制作公司教您重启进入沙盒的老域名
下一个:如何做网站?怎么基本建设公司的网站?网站建设又都需要什么?
民勤网站建设,民勤做网站,民勤网站设计