WordPress删除文章后同时自动删除文章内的媒体图片附件。
在删除WordPress文章之后,文章内的附件媒体图片往往都还存在你的空间或服务器上,时间久了会占用很大的磁盘空间。
那么我们怎么样才能在删除WordPress文章,附件也一并删除呢?
首先你得先进入你的主题目录,并找到functions.php插入如下代码即可自动删除文章内的媒体图片附件:
/* 删除文章时删除图片附件 */
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');
共有 0 条评论