WP删除文章同时删除缩略图和文章里的图片
Published
2023-08-09
浏览次数 : 43
<?php
/*
Plugin Name: Custom Post Cleanup
Description: Deletes post thumbnail and embedded images when a post is deleted.
Version: 1.0
Author: Your Name
*/
function delete_attached_images($post_id) {
// Get the post thumbnail ID
$thumbnail_id = get_post_thumbnail_id($post_id);
// Delete the post thumbnail
if ($thumbnail_id) {
wp_delete_attachment($thumbnail_id, true);
}
// Get embedded image IDs using regex or a more complex logic
$content = get_post_field('post_content', $post_id);
$pattern = '/<img[^>]+src=[\'"]([^\'"]+)[\'"][^>]*>/';
preg_match_all($pattern, $content, $matches);
if (!empty($matches[1])) {
foreach ($matches[1] as $image_url) {
$attachment_id = attachment_url_to_postid($image_url);
if ($attachment_id) {
wp_delete_attachment($attachment_id, true);
}
}
}
}
// Hook into post deletion action
add_action('before_delete_post', 'delete_attached_images');
- 标签1
- 标签1
- 标签1