函数文档

wp_ajax_save_attachment_order()

💡 云策文档标注

概述

wp_ajax_save_attachment_order() 是一个 WordPress AJAX 处理函数,用于保存附件顺序。它通过接收 POST 请求中的参数,验证权限和安全性,然后更新附件的 menu_order 字段。

关键要点

  • 函数通过 AJAX 处理附件顺序的保存,确保用户有编辑权限并验证 nonce 安全性。
  • 核心逻辑包括检查 post_id、attachments 参数,使用 wp_update_post() 更新每个附件的 menu_order。
  • 函数在验证失败或权限不足时返回 JSON 错误,成功时返回 JSON 成功响应。

代码示例

function wp_ajax_save_attachment_order() {
    if ( ! isset( $_REQUEST['post_id'] ) ) {
        wp_send_json_error();
    }

    $post_id = absint( $_REQUEST['post_id'] );
    if ( ! $post_id ) {
        wp_send_json_error();
    }

    if ( empty( $_REQUEST['attachments'] ) ) {
        wp_send_json_error();
    }

    check_ajax_referer( 'update-post_' . $post_id, 'nonce' );

    $attachments = $_REQUEST['attachments'];

    if ( ! current_user_can( 'edit_post', $post_id ) ) {
        wp_send_json_error();
    }

    foreach ( $attachments as $attachment_id => $menu_order ) {
        if ( ! current_user_can( 'edit_post', $attachment_id ) ) {
            continue;
        }

        $attachment = get_post( $attachment_id );

        if ( ! $attachment ) {
            continue;
        }

        if ( 'attachment' !== $attachment->post_type ) {
            continue;
        }

        wp_update_post(
            array(
                'ID'         => $attachment_id,
                'menu_order' => $menu_order,
            )
        );
    }

    wp_send_json_success();
}

注意事项

  • 函数依赖于 $_REQUEST 数组获取参数,需确保 AJAX 请求正确传递 post_id、attachments 和 nonce。
  • 权限检查包括对父文章和每个附件的编辑能力,避免未授权访问。
  • 使用 check_ajax_referer() 验证 nonce,增强安全性防止 CSRF 攻击。

📄 原文内容

Handles saving the attachment order via AJAX.

Source

function wp_ajax_save_attachment_order() {
	if ( ! isset( $_REQUEST['post_id'] ) ) {
		wp_send_json_error();
	}

	$post_id = absint( $_REQUEST['post_id'] );
	if ( ! $post_id ) {
		wp_send_json_error();
	}

	if ( empty( $_REQUEST['attachments'] ) ) {
		wp_send_json_error();
	}

	check_ajax_referer( 'update-post_' . $post_id, 'nonce' );

	$attachments = $_REQUEST['attachments'];

	if ( ! current_user_can( 'edit_post', $post_id ) ) {
		wp_send_json_error();
	}

	foreach ( $attachments as $attachment_id => $menu_order ) {
		if ( ! current_user_can( 'edit_post', $attachment_id ) ) {
			continue;
		}

		$attachment = get_post( $attachment_id );

		if ( ! $attachment ) {
			continue;
		}

		if ( 'attachment' !== $attachment->post_type ) {
			continue;
		}

		wp_update_post(
			array(
				'ID'         => $attachment_id,
				'menu_order' => $menu_order,
			)
		);
	}

	wp_send_json_success();
}

Changelog

Version Description
3.5.0 Introduced.