Creating Custom Fields Using the WordPress REST API

In this tutorial, I’ll show you how to create custom fields when using the WordPress REST API. We’ll create a single-file plugin that registers the custom fields so that you can create them when creating or updating posts remotely.

Let’s go.

Step 1: Creating a Single-File Plugin

First, let’s create a single-file plugin to register and expose our custom fields.

  • Create a new file named custom-fields-rest-api.php in the /wp-content/plugins/ directory of your WordPress installation.
  • Add the following code to the custom-fields-rest-api.php file:
<?php
/**
 * Plugin Name: Custom Fields REST API
 * Description: Expose custom fields in the WordPress REST API.
 * Version: 1.0
 * Author: Your Name
 * Author URI: https://example.com
 */
function register_custom_meta_fields() {
    register_meta('post', 'foo', array(
        'show_in_rest' => true,
        'single' => true,
        'type' => 'string',
    ));
    // Register additional custom fields by calling register_meta with their keys.
    // Example: register_meta('post', 'another_custom_field_key', array(...));
}
add_action('init', 'register_custom_meta_fields');

Replace Your Name and https://example.com with your actual name and website URL. Replace 'foo' with the actual custom field key you want to expose. If you have multiple custom fields, you can register each of them by calling the register_meta function with their respective keys inside the register_custom_meta_fields function.

Step 2: Activating the Plugin

After creating the single-file plugin, follow these steps to activate it:

  • Log in to your WordPress admin panel and go to the Plugins menu.
  • Find the Custom Fields REST API plugin in the list and click Activate.

Step 3: Verifying Custom Fields in the REST API

With the plugin activated, your custom fields should now be exposed in the REST API.

To verify, access the post’s API endpoint (e.g., http://example.com/wp-json/wp/v2/posts/{id}) and check if your custom field is present in the response.

You can also include it when creating or updating a post using the REST API.

Step4: Add the Meta Query Feature (Optional)

By default, you won’t be able to filter posts from http://example.com/wp-json/wp/v2/posts/based on a custom field value.

If you want to enable this feature, check my Filter WordPress REST API Posts by Custom Meta Key and Value article.

Refreshing Permalinks (Optional)

If you make any changes to the plugin code or experience issues with the REST API endpoints, you might need to refresh your permalinks. This can help ensure the REST API endpoints are updated accordingly. To do this:

  • Go to Settings > Permalinks in your WordPress admin panel.
  • Click the “Save Changes” button without making any modifications.

Conclusion

An there you have it! Posting custom fields while using the WordPress REST API.