封装Attach / Detach操作的逻辑

原型

wp_media_attach_action( int $parent_id, string $action = 'attach' )

参数

$parent_id (int) (Required) 附件父ID。

$action (string) (Optional)  附加/分离操作。接受’附加’或’分离’。

源文件

路径:wp-admin/includes/media.php

<?php
...
function wp_media_attach_action( $parent_id, $action = 'attach' ) {
	global $wpdb;
	if ( ! $parent_id ) {
		return;
	}
	if ( ! current_user_can( 'edit_post', $parent_id ) ) {
		wp_die( __( 'Sorry, you are not allowed to edit this post.' ) );
	}
	$ids = array();
	foreach ( (array) $_REQUEST['media'] as $att_id ) {
		$att_id = (int) $att_id;
		if ( ! current_user_can( 'edit_post', $att_id ) ) {
			continue;
		}
		$ids[] = $att_id;
	}
	if ( ! empty( $ids ) ) {
		$ids_string = implode( ',', $ids );
		if ( 'attach' === $action ) {
			$result = $wpdb->query( $wpdb->prepare( "UPDATE $wpdb->posts SET post_parent = %d WHERE post_type = 'attachment' AND ID IN ( $ids_string )", $parent_id ) );
		} else {
			$result = $wpdb->query( "UPDATE $wpdb->posts SET post_parent = 0 WHERE post_type = 'attachment' AND ID IN ( $ids_string )" );
		}
		foreach ( $ids as $att_id ) {
			clean_attachment_cache( $att_id );
		}
	}
	if ( isset( $result ) ) {
		$location = 'upload.php';
		if ( $referer = wp_get_referer() ) {
			if ( false !== strpos( $referer, 'upload.php' ) ) {
				$location = remove_query_arg( array( 'attached', 'detach' ), $referer );
			}
		}
		$key = 'attach' === $action ? 'attached' : 'detach';
		$location = add_query_arg( array( $key => $result ), $location );
		wp_redirect( $location );
		exit;
	}
}
...
?>

其他

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