wordpress在删除文章的时候,并不会从服务器上将文章的图片和缩略图删除掉,久而久之就会产生很多没必要的图片,若是网站量大了,还会占用空间,将下面的代码放到 function.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');
使用时还是需要根据自己的实际情况来,若是想留着就没必要删掉啦。