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

扩展WordPress REST API:新增文章响应字段的代码放置与执行咨询

Adding Custom Fields to WordPress REST API Post Responses

Hey there! Glad you've already dug into the docs and have a grasp on what register_rest_field does—let's break down where to put that code and how it actually runs behind the scenes.

Where to Place Your Code

You’ve got two reliable options, each with their own use cases:

  • Child Theme's functions.php: If you’re working with a child theme (always use a child theme instead of the parent—updates will overwrite parent theme changes!), drop your code here. This is great for theme-specific customizations that you want tied to your site’s design.
  • Custom Plugin: This is the better long-term solution. Create a simple plugin file (like custom-rest-fields.php) in your wp-content/plugins/ folder, add a basic plugin header, then insert your code. Plugins are independent of themes, so switching themes or updating your current one won’t break your REST API tweaks. You can even toggle the functionality on/off easily.

How the Execution Works

WordPress uses hooks to trigger code at specific points in its lifecycle, and the key hook here is rest_api_init. You need to attach your field registration code to this action—this ensures your code runs right when the REST API is setting up, before any API requests are processed.

Here’s the play-by-play:

  1. When someone hits a REST endpoint (like /wp-json/wp/v2/posts), WordPress starts initializing the API system.
  2. It fires the rest_api_init hook, which runs all code hooked to it—including your register_rest_field call.
  3. Your custom field gets registered to the post endpoint.
  4. WordPress processes the request, fetches the post data, and includes your custom field in the final response.

Full Working Example

Let’s put this all together with a practical example: adding a custom_author_bio field to post responses that pulls the author’s bio from their user profile.

// Hook our code to run when the REST API initializes
add_action('rest_api_init', function () {
    // Register the custom field for posts
    register_rest_field('post', 'custom_author_bio', [
        // Callback to fetch the field value
        'get_callback' => function ($post_data) {
            $author_id = $post_data['author'];
            $author = get_userdata($author_id);
            return !empty($author->description) ? $author->description : 'No bio available.';
        },
        // Optional: Allow updating the bio via API requests
        'update_callback' => function ($new_bio, $post) {
            $author_id = $post->post_author;
            return wp_update_user([
                'ID' => $author_id,
                'description' => $new_bio
            ]);
        },
        // Define the field schema (helps with API documentation)
        'schema' => [
            'description' => 'A custom bio for the post author',
            'type' => 'string'
        ]
    ]);
});

Drop this code in your child theme’s functions.php or custom plugin, activate the plugin if you went that route, then test your /wp-json/wp/v2/posts endpoint—you’ll see the custom_author_bio field in every post object.

内容的提问来源于stack exchange,提问作者emh

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.20 11:28:32