WordPress如何在删除文章时自动删除文章内的图片附件

摘要

并不是每一个站长都有条件使用大容量服务器,更多WordPress的博主/站长使用的主机空间或是服务器容量不是特别的大,这时候为节省服务器空间我们可以尽量减少文件的数量……

并不是每一个站长都有条件使用大容量服务器,更多WordPress的博主/站长使用的主机空间或是服务器容量不是特别的大,这时候为节省服务器空间我们可以尽量减少文件的数量,尽可能的删除一些没用的媒体文件,今天WPTOO教程网给大家带来一篇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');
//删除文章时删除图片附件
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');
//删除文章时删除图片附件 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');

使用方法

将上面WordPress代码复制粘贴到自己主题的functions.php里即可。

© 版权声明
THE END
喜欢就支持一下吧
点赞0赞赏 分享
When your faith is stronger than your fears, you can make your dreams happen.
当你的信念强于你的胆怯时,你就可以将梦想变为现实了
评论 抢沙发
头像
欢迎您留下宝贵的见解!
提交
头像

昵称

取消
昵称表情代码图片

    暂无评论内容