wordpress删除文章自动删除文章中的附件图片

追格官方小助手/ 2022年03月11日/ WordPress/ 浏览 2433

wordpress删除文章自动删除文章中的附件图片,文章删除到垃圾箱并在垃圾箱内彻底删除,媒体库里那个文章内的图片也就不见了。


在WordPress主题目录下的functions.php文件中添加以下代码就可以实现:


//删除特色图片
$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 );
}


// 删除文章同步删除附件图片
function delete_post_and_attachments($post_ID) {
global $wpdb;


//删除附件图片
$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’);


发表评论

暂无评论,抢个沙发...

客服 工单