函数文档

wp_ajax_save_wporg_username()

💡 云策文档标注

概述

wp_ajax_save_wporg_username() 是一个 WordPress AJAX 处理函数,用于保存用户的 WordPress.org 用户名。它通过权限检查、安全验证和用户元数据更新来实现此功能。

关键要点

  • 函数通过 AJAX 处理保存 WordPress.org 用户名的请求。
  • 需要用户具备 install_themes 或 install_plugins 权限才能执行。
  • 使用 check_ajax_referer() 验证 AJAX 请求的安全性。
  • 从 $_REQUEST['username'] 获取用户名,并使用 wp_unslash() 处理。
  • 成功时调用 wp_send_json_success() 返回更新结果,失败时调用 wp_send_json_error()。

代码示例

function wp_ajax_save_wporg_username() {
    if ( ! current_user_can( 'install_themes' ) && ! current_user_can( 'install_plugins' ) ) {
        wp_send_json_error();
    }

    check_ajax_referer( 'save_wporg_username_' . get_current_user_id() );

    $username = isset( $_REQUEST['username'] ) ? wp_unslash( $_REQUEST['username'] ) : false;

    if ( ! $username ) {
        wp_send_json_error();
    }

    wp_send_json_success( update_user_meta( get_current_user_id(), 'wporg_favorites', $username ) );
}

注意事项

  • 函数自 WordPress 4.4.0 版本引入。
  • 相关函数包括 update_user_meta()、current_user_can()、wp_unslash()、check_ajax_referer()、wp_send_json_error()、wp_send_json_success() 和 get_current_user_id()。

📄 原文内容

Handles saving the user’s WordPress.org username via AJAX.

Source

function wp_ajax_save_wporg_username() {
	if ( ! current_user_can( 'install_themes' ) && ! current_user_can( 'install_plugins' ) ) {
		wp_send_json_error();
	}

	check_ajax_referer( 'save_wporg_username_' . get_current_user_id() );

	$username = isset( $_REQUEST['username'] ) ? wp_unslash( $_REQUEST['username'] ) : false;

	if ( ! $username ) {
		wp_send_json_error();
	}

	wp_send_json_success( update_user_meta( get_current_user_id(), 'wporg_favorites', $username ) );
}

Changelog

Version Description
4.4.0 Introduced.