• Hi all,

    we know that adding a custom field to a native route of the WP REST API is pretty easy, and it looks something like this:

    function user_favorites_count() {
        // Return the user's favorite count
    }
    
    add_action( 'rest_api_init', function () {
    
        register_rest_field( 'user', 'favorites_count', array(
            'get_callback' => 'user_favorites_count',
            'schema' => null
        ));
    
    });

    However, this does not seem to work for custom routes: for example, if I created a custom route named customer and wanted to use it instead of user as the register_rest_field, the favorites_count field does not get registered. So how do you add a custom field to a custom route?

Viewing 1 replies (of 1 total)
  • Moderator bcworkz

    (@bcworkz)

    You need to add an endpoint to your route. You still cannot use register_rest_field(), but your endpoint can do just about anything, so have it handle your field.

Viewing 1 replies (of 1 total)

The topic ‘WP REST API — Adding Custom Fields to Custom Route’ is closed to new replies.