没错,草根站长的福音,删除文章时自动删除其特色图片及图片附件内容,有效的节省空间资源,只压根几行代码就可以实现完全的文章内容净化,不需要再去媒体库里翻看对应的图片附件,精准且高效。
area data-settings="dblclick" readonly >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');area>1617function delete_post_and_attachments($post_ID) {global $wpdb;//删除特色图片$thumbnails = $wpdb->get_results( "SELECT * FROM $wpdb->postme
ta WHERE me
ta_key = '_thumbnail_id' AND post_id = $post_ID" );foreach ( $thumbnails as $thumbnail ) {wp_delete_attachment( $thumbnail->me
ta_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->postme
ta WHERE me
ta_key = '_thumbnail_id' AND post_id = $post_ID" );}add_action('before_delete_post', 'delete_post_and_attachments');
把代码复制添加到主题的函数文件functions.php中,如果在使用action delete_post而不是before_delete_post将导致删除文章后因媒体附件与文章关联已取消而无法正确删除。