• 0点赞

  • 0收藏

在当前WordPress模板函数文件functions.php中,添加以下代码即可轻松实现WordPress删除文章时自动删除文章内的图片附件。

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

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

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

 

版权声明:追格所提供的文章、图片等内容均为用户发布或互联网整理而来,仅供学习参考,如有侵犯您的版权,请联系我们www#zhuige.cn(#为@)删除。

发表评论

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

评论信息

TOP