删除或删除附件。

原型

wp_delete_attachment( int $post_id, bool $force_delete = false )

描述

永久删除附件时,也会删除该文件。删除将删除与附件关联的所有后置元字段,分类,注释等(主帖除外)。

参数

$post_id (int) (Required) 附件ID。

$force_delete (bool) (Optional)  是否绕过垃圾并强行删除。

返回值

(WP_Post|false|null)  发布成功数据,错误或失败时返回null。

源文件

路径:wp-includes/post.php

<?php
...
function wp_delete_attachment( $post_id, $force_delete = false ) {
	global $wpdb;
	$post = $wpdb->get_row( $wpdb->prepare( "SELECT * FROM $wpdb->posts WHERE ID = %d", $post_id ) );
	if ( ! $post ) {
		return $post;
	}
	$post = get_post( $post );
	if ( 'attachment' !== $post->post_type ) {
		return false;
	}
	if ( ! $force_delete && EMPTY_TRASH_DAYS && MEDIA_TRASH && 'trash' !== $post->post_status ) {
		return wp_trash_post( $post_id );
	}
	delete_post_meta($post_id, '_wp_trash_meta_status');
	delete_post_meta($post_id, '_wp_trash_meta_time');
	$meta = wp_get_attachment_metadata( $post_id );
	$backup_sizes = get_post_meta( $post->ID, '_wp_attachment_backup_sizes', true );
	$file = get_attached_file( $post_id );
	if ( is_multisite() )
		delete_transient( 'dirsize_cache' );
	/**
	 * Fires before an attachment is deleted, at the start of wp_delete_attachment().
	 *
	 * @since 2.0.0
	 *
	 * @param int $post_id Attachment ID.
	 */
	do_action( 'delete_attachment', $post_id );
	wp_delete_object_term_relationships($post_id, array('category', 'post_tag'));
	wp_delete_object_term_relationships($post_id, get_object_taxonomies($post->post_type));
	// Delete all for any posts.
	delete_metadata( 'post', null, '_thumbnail_id', $post_id, true );
	wp_defer_comment_counting( true );
	$comment_ids = $wpdb->get_col( $wpdb->prepare( "SELECT comment_ID FROM $wpdb->comments WHERE comment_post_ID = %d", $post_id ));
	foreach ( $comment_ids as $comment_id ) {
		wp_delete_comment( $comment_id, true );
	}
	wp_defer_comment_counting( false );
	$post_meta_ids = $wpdb->get_col( $wpdb->prepare( "SELECT meta_id FROM $wpdb->postmeta WHERE post_id = %d ", $post_id ));
	foreach ( $post_meta_ids as $mid )
		delete_metadata_by_mid( 'post', $mid );
	/** This action is documented in wp-includes/post.php */
	do_action( 'delete_post', $post_id );
	$result = $wpdb->delete( $wpdb->posts, array( 'ID' => $post_id ) );
	if ( ! $result ) {
		return false;
	}
	/** This action is documented in wp-includes/post.php */
	do_action( 'deleted_post', $post_id );
	wp_delete_attachment_files( $post_id, $meta, $backup_sizes, $file );
	clean_post_cache( $post );
	return $post;
}
...
?>

其他

英文文档:https://developer.wordpress.org/reference/functions/wp_delete_attachment/