函数文档

wp_ajax_set_post_thumbnail()

💡 云策文档标注

概述

wp_ajax_set_post_thumbnail() 是一个 WordPress AJAX 处理函数,用于设置或删除文章的精选图像(特色图像)。它处理来自前端的 AJAX 请求,验证用户权限和请求安全性,并返回相应的 HTML 或 JSON 响应。

关键要点

  • 函数通过 AJAX 处理设置或删除文章精选图像,支持新旧两种请求格式(JSON 和非 JSON)。
  • 验证当前用户是否有编辑文章的权限(使用 current_user_can()),并检查 AJAX 引用(使用 check_ajax_referer())以确保安全性。
  • 根据 thumbnail_id 的值(-1 表示删除,其他表示设置)调用 delete_post_thumbnail() 或 set_post_thumbnail() 函数,并返回 _wp_post_thumbnail_html() 生成的 HTML 或 JSON 响应。
  • 使用 wp_send_json_success() 或 wp_die() 返回结果,处理成功或失败情况。

代码示例

function wp_ajax_set_post_thumbnail() {
    $json = ! empty( $_REQUEST['json'] ); // New-style request.

    $post_id = (int) $_POST['post_id'];
    if ( ! current_user_can( 'edit_post', $post_id ) ) {
        wp_die( -1 );
    }

    $thumbnail_id = (int) $_POST['thumbnail_id'];

    if ( $json ) {
        check_ajax_referer( "update-post_$post_id" );
    } else {
        check_ajax_referer( "set_post_thumbnail-$post_id" );
    }

    if ( -1 === $thumbnail_id ) {
        if ( delete_post_thumbnail( $post_id ) ) {
            $return = _wp_post_thumbnail_html( null, $post_id );
            $json ? wp_send_json_success( $return ) : wp_die( $return );
        } else {
            wp_die( 0 );
        }
    }

    if ( set_post_thumbnail( $post_id, $thumbnail_id ) ) {
        $return = _wp_post_thumbnail_html( $thumbnail_id, $post_id );
        $json ? wp_send_json_success( $return ) : wp_die( $return );
    }

    wp_die( 0 );
}

注意事项

  • 函数依赖于 POST 参数 post_id 和 thumbnail_id,thumbnail_id 为 -1 时表示删除精选图像。
  • 安全性通过 current_user_can() 和 check_ajax_referer() 确保,防止未授权访问和 CSRF 攻击。
  • 返回格式根据请求类型(JSON 或非 JSON)使用 wp_send_json_success() 或 wp_die(),确保前端能正确处理响应。

📄 原文内容

Handles setting the featured image via AJAX.

Source

function wp_ajax_set_post_thumbnail() {
	$json = ! empty( $_REQUEST['json'] ); // New-style request.

	$post_id = (int) $_POST['post_id'];
	if ( ! current_user_can( 'edit_post', $post_id ) ) {
		wp_die( -1 );
	}

	$thumbnail_id = (int) $_POST['thumbnail_id'];

	if ( $json ) {
		check_ajax_referer( "update-post_$post_id" );
	} else {
		check_ajax_referer( "set_post_thumbnail-$post_id" );
	}

	if ( -1 === $thumbnail_id ) {
		if ( delete_post_thumbnail( $post_id ) ) {
			$return = _wp_post_thumbnail_html( null, $post_id );
			$json ? wp_send_json_success( $return ) : wp_die( $return );
		} else {
			wp_die( 0 );
		}
	}

	if ( set_post_thumbnail( $post_id, $thumbnail_id ) ) {
		$return = _wp_post_thumbnail_html( $thumbnail_id, $post_id );
		$json ? wp_send_json_success( $return ) : wp_die( $return );
	}

	wp_die( 0 );
}

Changelog

Version Description
3.1.0 Introduced.