wordpress 4.4.1删除文章同时删除图片附件以及特色图像

WordPress在删除文章时,文章内所上传到媒体库的图片等附件不会自动删除,时间久了之后占用了网站空间,备份网站文件也不划算。以下的代码可以实现在删除文章时自动删除文章图片附件以及特色图片,将代码放到当前主题inc/fn.php(wordpress 4.4.1版本),如果是老版本则修改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’);

 
合作联系邮箱:cofface#cofface.com(请将#替换为@)

转载请注明来源:Cofface Blog » wordpress 4.4.1删除文章同时删除图片附件以及特色图像

赞 (4) 打赏

感谢您的支持,我会继续努力的!

支付宝扫一扫打赏