函数文档

wp_ajax_set_attachment_thumbnail()

💡 云策文档标注

概述

wp_ajax_set_attachment_thumbnail() 是一个 WordPress AJAX 处理函数,用于为附件设置特色图像。它通过验证请求、转换 URL 为附件 ID,并调用 set_post_thumbnail() 来实现功能。

关键要点

  • 函数通过 AJAX 处理设置附件特色图像的请求,确保数据安全性和用户权限。
  • 核心流程包括验证输入参数(如 urls 数组和 thumbnail_id)、检查 AJAX nonce、将附件 URL 转换为 post ID,并循环设置特色图像。
  • 使用相关函数如 attachment_url_to_postid()、set_post_thumbnail()、current_user_can() 和 check_ajax_referer() 来支持功能实现。
  • 函数返回 JSON 响应,指示操作成功或失败,便于前端处理。

代码示例

function wp_ajax_set_attachment_thumbnail() {
	if ( empty( $_POST['urls'] ) || ! is_array( $_POST['urls'] ) ) {
		wp_send_json_error();
	}

	$thumbnail_id = (int) $_POST['thumbnail_id'];
	if ( empty( $thumbnail_id ) ) {
		wp_send_json_error();
	}

	if ( false === check_ajax_referer( 'set-attachment-thumbnail', '_ajax_nonce', false ) ) {
		wp_send_json_error();
	}

	$post_ids = array();
	// For each URL, try to find its corresponding post ID.
	foreach ( $_POST['urls'] as $url ) {
		$post_id = attachment_url_to_postid( $url );
		if ( ! empty( $post_id ) ) {
			$post_ids[] = $post_id;
		}
	}

	if ( empty( $post_ids ) ) {
		wp_send_json_error();
	}

	$success = 0;
	// For each found attachment, set its thumbnail.
	foreach ( $post_ids as $post_id ) {
		if ( ! current_user_can( 'edit_post', $post_id ) ) {
			continue;
		}

		if ( set_post_thumbnail( $post_id, $thumbnail_id ) ) {
			++$success;
		}
	}

	if ( 0 === $success ) {
		wp_send_json_error();
	} else {
		wp_send_json_success();
	}

	wp_send_json_error();
}

注意事项

  • 函数依赖于 $_POST 参数,需确保前端正确传递 urls(数组)和 thumbnail_id(整数)。
  • 使用 check_ajax_referer() 验证 AJAX 请求,防止 CSRF 攻击,nonce 应基于 'set-attachment-thumbnail' 生成。
  • 用户必须具有 'edit_post' 权限才能为附件设置特色图像,否则操作会被跳过。
  • 函数在 WordPress 4.0.0 版本引入,兼容性需考虑。

📄 原文内容

Handles setting the featured image for an attachment via AJAX.

Description

See also

Source

function wp_ajax_set_attachment_thumbnail() {
	if ( empty( $_POST['urls'] ) || ! is_array( $_POST['urls'] ) ) {
		wp_send_json_error();
	}

	$thumbnail_id = (int) $_POST['thumbnail_id'];
	if ( empty( $thumbnail_id ) ) {
		wp_send_json_error();
	}

	if ( false === check_ajax_referer( 'set-attachment-thumbnail', '_ajax_nonce', false ) ) {
		wp_send_json_error();
	}

	$post_ids = array();
	// For each URL, try to find its corresponding post ID.
	foreach ( $_POST['urls'] as $url ) {
		$post_id = attachment_url_to_postid( $url );
		if ( ! empty( $post_id ) ) {
			$post_ids[] = $post_id;
		}
	}

	if ( empty( $post_ids ) ) {
		wp_send_json_error();
	}

	$success = 0;
	// For each found attachment, set its thumbnail.
	foreach ( $post_ids as $post_id ) {
		if ( ! current_user_can( 'edit_post', $post_id ) ) {
			continue;
		}

		if ( set_post_thumbnail( $post_id, $thumbnail_id ) ) {
			++$success;
		}
	}

	if ( 0 === $success ) {
		wp_send_json_error();
	} else {
		wp_send_json_success();
	}

	wp_send_json_error();
}

Changelog

Version Description
4.0.0 Introduced.