Function and usage of register_rest_field() in wordpress

Question

Answers ( 1 )

    0
    2024-01-08T12:11:15+00:00

    The register_rest_field() function in WordPress is a powerful tool used to extend the WordPress REST API by adding custom fields to existing WordPress objects like posts, terms, or comments. Here's a detailed explanation and a sample usage:

    Function:

    register_rest_field() registers a new field on an existing WordPress object type. This function is particularly useful for developers who want to add custom data to API responses.

    Parameters:

    1. $object_type (string|array, required): This parameter specifies the object(s) the field is being registered to. It can be a string or an array of strings. Examples of object types include "post", "term", "comment", etc.

    2. $attribute (string, required): This is the name of the attribute you're adding. It's the key that will be used to access the value of the field in the REST API response.

    3. $args (array, optional): An array of arguments used to handle the registered field. This array can contain the following keys:

      • get_callback (callable|null, optional): The callback function used for retrieving the field value. If null, the field will not be returned in the response. This function receives the object data as its argument.
      • update_callback (callable|null, optional): The callback function used to set and update the field value. If null, the value cannot be set or updated. This function is passed the model object, like WP_Post.
      • schema (array|null, optional): The schema for this field. If null, no schema entry will be returned. The schema helps API clients understand what type of data to expect.

    Default Value:

    • array()

    Sample Usage:

    Suppose you want to add a custom field to posts that shows a simple text message.

    function my_get_post_meta_for_api( $object ) {
        // Assuming the custom field is stored as post meta.
        return get_post_meta( $object['id'], 'my_custom_field', true );
    }
    
    function my_update_post_meta_for_api( $value, $object ) {
        // Updating the custom field.
        return update_post_meta( $object->ID, 'my_custom_field', strip_tags( $value ) );
    }
    
    add_action( 'rest_api_init', function() {
        register_rest_field( 'post', 'my_custom_field', array(
            'get_callback'    => 'my_get_post_meta_for_api',
            'update_callback' => 'my_update_post_meta_for_api',
            'schema'          => null,
        ));
    });
    

    In this example, the register_rest_field function is used to add a new field called my_custom_field to all WordPress posts. The get_callback function my_get_post_meta_for_api retrieves the value of this field, and the update_callback function my_update_post_meta_for_api updates its value. This way, you can easily add and manipulate custom data in your REST API responses.

Leave an answer