4

wordpress文章删除时自动删除内容文章中的图片和附件内容

 2 years ago
source link: https://www.huhexian.com/30699.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

wordpress文章删除时自动删除内容文章中的图片和附件内容

2022-03-0810:09:30评论783字

这个功能我还是很喜欢的因为前两天网站搬家,我检查了一下 uploads 图片文件夹,光图片就已经占用半个服务器空间,因此有了这个文章删除时自动删掉图片附件还是很香的,可以很大程度减缓服务器压力和时间成本。

wordpress文章删除时自动删除内容文章中的图片和附件内容

1、只需将下面的 PHP 代码加入到主题目录下的functions.php 文件底部就可以了。

  1. //删除文章时删除图片附件开始
  2. function delete_post_and_attachments($post_ID) {
  3. global $wpdb;
  4. //删除特色图片
  5. $thumbnails = $wpdb->get_results( "SELECT * FROM $wpdb->postmeta WHERE meta_key = '_thumbnail_id' AND post_id = $post_ID" );
  6. foreach ( $thumbnails as $thumbnail ) {
  7. wp_delete_attachment( $thumbnail->meta_value, true );
  8. //删除图片附件
  9. $attachments = $wpdb->get_results( "SELECT * FROM $wpdb->posts WHERE post_parent = $post_ID AND post_type = 'attachment'" );
  10. foreach ( $attachments as $attachment ) {
  11. wp_delete_attachment( $attachment->ID, true );
  12. $wpdb->query( "DELETE FROM $wpdb->postmeta WHERE meta_key = '_thumbnail_id' AND post_id = $post_ID" );
  13. add_action('before_delete_post', 'delete_post_and_attachments');
  14. //删除文章时删除图片附件结束

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK