扩展WordPress REST API:新增文章响应字段的代码放置与执行咨询
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 yourwp-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:
- When someone hits a REST endpoint (like
/wp-json/wp/v2/posts), WordPress starts initializing the API system. - It fires the
rest_api_inithook, which runs all code hooked to it—including yourregister_rest_fieldcall. - Your custom field gets registered to the post endpoint.
- 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

