函数文档

wp_ajax_image_editor()

💡 云策文档标注

概述

wp_ajax_image_editor() 是一个 WordPress AJAX 处理函数,用于管理图像编辑操作,包括保存、缩放和恢复。它通过验证用户权限和 AJAX 请求,调用相关图像编辑函数,并返回 JSON 响应。

关键要点

  • 函数处理 AJAX 图像编辑请求,支持 'save'、'scale' 和 'restore' 操作。
  • 验证附件 ID 和用户权限(使用 current_user_can('edit_post')),并检查 AJAX 引用(check_ajax_referer)。
  • 调用 wp_save_image()、wp_restore_image() 和 wp_image_editor() 等函数执行具体编辑任务。
  • 使用 wp_send_json_success() 和 wp_send_json_error() 返回 JSON 响应,包含消息和 HTML 内容。
  • 引入于 WordPress 3.1.0 版本。

代码示例

function wp_ajax_image_editor() {
	$attachment_id = (int) $_POST['postid'];

	if ( empty( $attachment_id ) || ! current_user_can( 'edit_post', $attachment_id ) ) {
		wp_die( -1 );
	}

	check_ajax_referer( "image_editor-$attachment_id" );
	require_once ABSPATH . 'wp-admin/includes/image-edit.php';

	$msg = false;

	switch ( $_POST['do'] ) {
		case 'save':
			$msg = wp_save_image( $attachment_id );
			if ( ! empty( $msg->error ) ) {
				wp_send_json_error( $msg );
			}

			wp_send_json_success( $msg );
			break;
		case 'scale':
			$msg = wp_save_image( $attachment_id );
			break;
		case 'restore':
			$msg = wp_restore_image( $attachment_id );
			break;
	}

	ob_start();
	wp_image_editor( $attachment_id, $msg );
	$html = ob_get_clean();

	if ( ! empty( $msg->error ) ) {
		wp_send_json_error(
			array(
				'message' => $msg,
				'html'    => $html,
			)
		);
	}

	wp_send_json_success(
		array(
			'message' => $msg,
			'html'    => $html,
		)
	);
}

注意事项

  • 函数依赖于 $_POST['postid'] 和 $_POST['do'] 参数,确保 AJAX 请求正确传递这些值。
  • 权限检查使用 current_user_can('edit_post', $attachment_id),确保用户有权编辑附件。
  • 错误处理通过 wp_send_json_error() 返回,开发者需在前端处理 JSON 响应。

📄 原文内容

Handles image editing via AJAX.

Source

function wp_ajax_image_editor() {
	$attachment_id = (int) $_POST['postid'];

	if ( empty( $attachment_id ) || ! current_user_can( 'edit_post', $attachment_id ) ) {
		wp_die( -1 );
	}

	check_ajax_referer( "image_editor-$attachment_id" );
	require_once ABSPATH . 'wp-admin/includes/image-edit.php';

	$msg = false;

	switch ( $_POST['do'] ) {
		case 'save':
			$msg = wp_save_image( $attachment_id );
			if ( ! empty( $msg->error ) ) {
				wp_send_json_error( $msg );
			}

			wp_send_json_success( $msg );
			break;
		case 'scale':
			$msg = wp_save_image( $attachment_id );
			break;
		case 'restore':
			$msg = wp_restore_image( $attachment_id );
			break;
	}

	ob_start();
	wp_image_editor( $attachment_id, $msg );
	$html = ob_get_clean();

	if ( ! empty( $msg->error ) ) {
		wp_send_json_error(
			array(
				'message' => $msg,
				'html'    => $html,
			)
		);
	}

	wp_send_json_success(
		array(
			'message' => $msg,
			'html'    => $html,
		)
	);
}

Changelog

Version Description
3.1.0 Introduced.