功能介绍

站点内的文章肯定不止一篇两篇,媒体内的图片肯定也是不止一张两张,当我想删除一篇文章时又会头疼这个图片怎么去删除,以下方法就很好的去解决这个问题,当我去删除这篇文章时,这篇文章内的图片也会同步删除!

配置教程

首先利用宝塔或则FTP打开/inc/options下的admin-options.php文件把下面代码放在20行左右

  1. array(
  2. ‘id’ => ‘is_delete_article’,
  3. ‘type’ => ‘switcher’,
  4. ‘title’ => ‘删除文章同时删除图片’,
  5. ‘label’ => ‘启用后在删除文章时会删除文章对应的图片’,
  6. ‘default’ => false,
  7. ),

最后在主题根目录下打开functions.php将以下代码放在最后即可

  1. //+———————————————————————-
  2. //| 删除文章时删除图片附件
  3. //+———————————————————————-
  4. function delete_post_and_attachments($post_ID) {
  5. global $wpdb;
  6. //删除特色图片
  7. $thumbnails = $wpdb->get_results( “SELECT * FROM $wpdb->postmeta WHERE meta_key = ‘_thumbnail_id’ AND post_id = $post_ID” );
  8. foreach ( $thumbnails as $thumbnail ) {
  9. wp_delete_attachment( $thumbnail->meta_value, true );
  10. }
  11. //删除图片附件
  12. $attachments = $wpdb->get_results( “SELECT * FROM $wpdb->posts WHERE post_parent = $post_ID AND post_type = ‘attachment'” );
  13. foreach ( $attachments as $attachment ) {
  14. wp_delete_attachment( $attachment->ID, true );
  15. }
  16. $wpdb->query( “DELETE FROM $wpdb->postmeta WHERE meta_key = ‘_thumbnail_id’ AND post_id = $post_ID” );
  17. }
  18. if(_cao(‘is_delete_article’) ){
  19. add_action(‘before_delete_post’, ‘delete_post_and_attachments’);
  20. }

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注