You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在WordPress插件JS文件中访问usermeta表?能否用REST API替代PHP用户元函数?

Working with WordPress User Meta in JavaScript (via REST API)

Great question! Since you're already comfortable using PHP's get_user_meta(), add_user_meta(), and update_user_meta() to work with the usermeta table, replicating that functionality in your WordPress plugin's JavaScript files is totally feasible—the WordPress REST API is the official, clean way to do this. Let's walk through how to set it up and use it.

Step 1: Register Your User Meta Field for REST API Access

By default, WordPress doesn't expose all user meta fields to the REST API for security reasons. So first, you need to register the specific meta keys you want to interact with from JavaScript. Do this in your plugin's PHP code:

// Register a custom user meta field for REST API access
function my_plugin_register_user_meta() {
    register_meta(
        'user',
        'my_custom_user_meta_key', // Replace with your actual meta key
        array(
            'show_in_rest' => true,
            'single' => true, // Set to false if your meta is an array
            'type' => 'string', // Adjust based on your data type (int, bool, etc.)
            'auth_callback' => function() {
                // Ensure only authorized users can access/edit this meta
                return current_user_can('edit_user', get_current_user_id());
            }
        )
    );
}
add_action('rest_api_init', 'my_plugin_register_user_meta');

This tells WordPress to include your meta field in user API responses and allow modifications via API requests.

Step 2: Interact with User Meta in JavaScript

Once your meta field is registered, you can use standard fetch requests (or WordPress's built-in wp-api utilities) to read, update, or add user meta. Don't forget to handle authentication with a WordPress nonce to prevent CSRF attacks.

First: Load the REST Nonce (Critical for Authentication)

In your PHP, pass the REST nonce to your JavaScript file using wp_localize_script:

function my_plugin_enqueue_scripts() {
    wp_enqueue_script('my-plugin-js', plugin_dir_url(__FILE__) . 'js/my-plugin.js', array('wp-api'), '1.0', true);
    
    // Pass REST nonce and current user ID to JS
    wp_localize_script('my-plugin-js', 'MyPluginData', array(
        'restNonce' => wp_create_nonce('wp_rest'),
        'currentUserId' => get_current_user_id()
    ));
}
add_action('wp_enqueue_scripts', 'my_plugin_enqueue_scripts');

Example 1: Get User Meta Data

Fetch the current user's meta data (or any user by ID):

async function getUserMeta(userId) {
    try {
        const response = await fetch(`/wp-json/wp/v2/users/${userId}`, {
            headers: {
                'X-WP-Nonce': MyPluginData.restNonce
            }
        });
        
        if (!response.ok) throw new Error('Failed to fetch user data');
        
        const userData = await response.json();
        // Access your meta field
        const customMetaValue = userData.meta.my_custom_user_meta_key;
        console.log('Custom meta value:', customMetaValue);
        return customMetaValue;
    } catch (error) {
        console.error('Error fetching user meta:', error);
    }
}

// Use it for the current user
getUserMeta(MyPluginData.currentUserId);

Example 2: Update/Add User Meta Data

Send a PUT request to update an existing meta field, or add a new one if it doesn't exist:

async function updateUserMeta(userId, metaKey, metaValue) {
    try {
        const response = await fetch(`/wp-json/wp/v2/users/${userId}`, {
            method: 'PUT',
            headers: {
                'X-WP-Nonce': MyPluginData.restNonce,
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({
                meta: {
                    [metaKey]: metaValue
                }
            })
        });
        
        if (!response.ok) throw new Error('Failed to update user meta');
        
        const updatedUser = await response.json();
        console.log('Updated user meta:', updatedUser.meta[metaKey]);
        return updatedUser;
    } catch (error) {
        console.error('Error updating user meta:', error);
    }
}

// Update the current user's custom meta
updateUserMeta(MyPluginData.currentUserId, 'my_custom_user_meta_key', 'New value for my meta');

Example 3: Delete User Meta Data

To delete a meta field, set its value to null in a PUT request:

async function deleteUserMeta(userId, metaKey) {
    try {
        const response = await fetch(`/wp-json/wp/v2/users/${userId}`, {
            method: 'PUT',
            headers: {
                'X-WP-Nonce': MyPluginData.restNonce,
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({
                meta: {
                    [metaKey]: null
                }
            })
        });
        
        if (!response.ok) throw new Error('Failed to delete user meta');
        
        console.log(`Meta field ${metaKey} deleted successfully`);
    } catch (error) {
        console.error('Error deleting user meta:', error);
    }
}

// Delete the custom meta from current user
deleteUserMeta(MyPluginData.currentUserId, 'my_custom_user_meta_key');

Key Notes

  • Permissions: Make sure your auth_callback in register_meta() correctly restricts access to only users who should be able to edit the meta (e.g., admins, or the user themselves).
  • Multi-Value Meta: If your meta field is an array (set single to false in register_meta()), you can pass an array as the value in your JS request.
  • Error Handling: Always include try/catch blocks and check response statuses to handle cases like network errors or permission issues.

内容的提问来源于stack exchange,提问作者Tobias Samsøe Sørensen

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.09 12:03:15