wordpress删除文章时同时删除文章的图片

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

 

 

THE END
分享
wordpress删除文章时同时删除文章的图片
wordpress在删除文章的时候,并不会从服务器上将文章的图片和缩略图删除掉,久而久之就会产生很多没必要的图片,若是网站量大了,还会占用空间,将下面的代码……
<<上一篇
下一篇>>