LMS & eLearning

Adding Custom Fields to LearnDash REST API Responses

Three ways to expose extra data on LearnDash REST API v2 responses: the learndash_rest_register_fields action, a plain register_rest_field call, and metabox fields flagged show_in_rest. How each works and when to use it.

Adding Custom Fields to LearnDash REST API Responses

Sooner or later an integration needs a field LearnDash does not send: a SKU from the store, a cohort start date, an instructor record, a computed completion count. The REST API v2 in LearnDash 4.18.0.1 gives you three places to add it. One is a LearnDash action fired while each controller registers its fields, one is WordPress's ordinary register_rest_field(), and one is LearnDash's own metabox field system, which turns a settings field into a REST field automatically. They produce the same result for a client but differ in where the data lives and how updates are handled. This guide explains how the v2 controllers assemble their fields, then shows each approach with working code.

How v2 controllers build their fields

Every v2 post type controller, from courses and lessons to groups, essays and exams, calls register_fields() at the start of register_routes(). In the courses controller that method does two things: it calls register_fields_metabox(), which instantiates the course settings metaboxes and converts every field flagged show_in_rest into a REST field, and then it fires do_action( 'learndash_rest_register_fields', $this->post_type, $this ). The metabox conversion registers each field under its field_key if one is set in its rest_args schema, otherwise under the settings key, with a default get_callback of get_rest_settings_field_value() and update_callback of update_rest_settings_field_value(). Those two methods read and write through learndash_get_setting() and learndash_update_setting(), which is why price_type on a course response is the same value the course edit screen shows.

When the controller builds its schema or collects additional fields, it temporarily swaps the global list of registered REST fields for the post type: it removes legacy fields from the post type's registration arguments that are flagged show_in_rest, adds its own metabox-derived fields, calls the parent, then restores the global. Fields you register yourself under a different key survive that swap, which is what makes the first two approaches below work.

Approach one: the learndash_rest_register_fields action

This is the LearnDash-native hook. It receives the post type slug and the controller instance, and it fires at the right moment, after the metabox fields exist and before routes are registered, so your field appears in the schema that OPTIONS requests and the block editor read.

<?php
/**
 * Expose a cohort start date on course responses and accept updates to it.
 */
add_action(
    'learndash_rest_register_fields',
    function ( $post_type, $controller ) {
        if ( learndash_get_post_type_slug( 'course' ) !== $post_type ) {
            return;
        }

        register_rest_field(
            $post_type,
            'cohort_starts',
            array(
                'get_callback'    => function ( $post_data ) {
                    return (string) get_post_meta( $post_data['id'], '_cohort_starts', true );
                },
                'update_callback' => function ( $value, $post ) {
                    if ( ! current_user_can( 'edit_post', $post->ID ) ) {
                        return new WP_Error( 'rest_forbidden', 'Not allowed.', array( 'status' => 403 ) );
                    }
                    $value = sanitize_text_field( $value );
                    if ( '' !== $value && false === strtotime( $value ) ) {
                        return new WP_Error( 'rest_invalid_param', 'Invalid date.', array( 'status' => 400 ) );
                    }
                    update_post_meta( $post->ID, '_cohort_starts', $value );
                    return true;
                },
                'schema'          => array(
                    'description' => 'Cohort start date, Y-m-d.',
                    'type'        => 'string',
                    'context'     => array( 'view', 'edit' ),
                ),
            )
        );
    },
    10,
    2
);

The $controller argument is useful when you want to read the controller's metabox field list or reuse its callbacks, but most code only needs the post type. Because the action fires once per controller during rest_api_init, there is no need to hook rest_api_init yourself. Note that the action fires for the v2 controllers only; v1 routes do not run it.

Approach two: plain register_rest_field

LearnDash post types are WordPress post types, so a field registered on rest_api_init with register_rest_field( 'sfwd-courses', ... ) is also included by the v2 courses controller, as long as its key does not collide with a LearnDash setting flagged for REST. This is the approach to use when the same field should appear on several post types or when the code must not depend on LearnDash being active. The disadvantage is ordering: rest_api_init callbacks run in priority order, and LearnDash registers its controllers from its own rest_api_init hook, so a field you register at default priority is normally present before the controller builds its schema, but a field registered late may be missing from OPTIONS output while still being returned on GET. Register at priority 5 if you see that.

Both approaches add a top-level key to the response. If you prefer to use the WordPress meta object instead, register the meta with register_post_meta() and show_in_rest true; LearnDash's post types support custom fields, so the meta appears under meta in the response and is writable with the standard rules. That costs you nothing in code but puts the field one level deeper for clients.

Approach three: a metabox field with show_in_rest

When the data is a real LearnDash setting, something editors should see on the course edit screen as well as in the API, add it to a LearnDash metabox. The metabox classes build their field list in load_settings_fields() and pass it through the filter learndash_settings_fields with the metabox key as the second argument. A field added there with a rest block is picked up by register_fields_metabox() and becomes a REST field with LearnDash's own callbacks, stored in the post's settings meta like any other setting.

<?php
add_filter(
    'learndash_settings_fields',
    function ( $fields, $metabox_key ) {
        if ( 'learndash-course-display-content-settings' !== $metabox_key ) {
            return $fields;
        }

        $fields['course_instructor_name'] = array(
            'name'      => 'course_instructor_name',
            'label'     => 'Instructor name',
            'type'      => 'text',
            'value'     => '',
            'help_text' => 'Shown on the course card and returned by the REST API.',
            'rest'      => array(
                'show_in_rest' => LearnDash_REST_API::enabled(),
                'rest_args'    => array(
                    'schema' => array(
                        'field_key'   => 'instructor_name',
                        'description' => 'Instructor name',
                        'type'        => 'string',
                        'default'     => '',
                    ),
                ),
            ),
        );

        return $fields;
    },
    10,
    2
);

The metabox key for a course's Display and Content Options metabox is the one used above; read the key from the metabox class's settings_metabox_key property when targeting another metabox. The field then reads and writes through learndash_get_setting( $post_id, 'course_instructor_name' ), appears in the admin, and is returned as instructor_name on the course response, with updates accepted from anyone the controller allows to edit the course. The settings API guide explains the field types the metaboxes support.

Choosing

  • Computed or external values such as counts, store prices or CRM IDs: approach one, with a get_callback only and no update_callback.
  • Data shared across post types or managed by a plugin that must not depend on LearnDash: approach two, or register_post_meta().
  • Settings editors manage on the edit screen: approach three, so the admin and the API stay in step.

Whatever you choose, give the schema a context, sanitise in the update callback, and check capabilities yourself; the controller's permission check protects the request, not your field. For the read side of the same responses see our guide to fetching courses and lessons over REST, and for adding entirely new routes rather than fields see building a custom LearnDash REST controller.

When to get help

A field or two is an hour's work. Exposing a whole custom data model, keeping it consistent with the block editor's course settings panels, or versioning fields for external consumers is development work our LearnDash services team and LearnDash development practice handle, and a LearnDash developer can also audit which existing settings you expose before opening the API to partners.

Frequently asked questions

Which hook adds fields to LearnDash REST API responses?

The action learndash_rest_register_fields, fired by each v2 post type controller with the post type and the controller instance. Call register_rest_field() inside it.

Does a plain register_rest_field work on sfwd-courses?

Yes, as long as the key does not collide with a LearnDash setting flagged for REST. Register it on rest_api_init at an early priority.

How do I make a setting appear both in the admin and the API?

Add it to a LearnDash metabox through the learndash_settings_fields filter with a rest block whose show_in_rest is true; LearnDash registers the REST field for you.

Will my custom field show on v1 routes?

Fields registered with register_rest_field() appear wherever WordPress serialises that post type, including v1. The learndash_rest_register_fields action itself fires only from v2 controllers.

Add WorldWin Coder to your preferred sources

Add worldwincoder.com as a preferred source on Google, or open this article in your AI assistant to use it as a source.

· Developers and project managers

Articles written and reviewed by the developers and project managers at WorldWin Coder, who build and maintain websites, web applications and mobile apps on WordPress, Moodle, PHP, Laravel, CodeIgniter and Flutter.

Keep reading

Have something to build, fix or move?

Tell us where you are. A developer reads every inquiry, and you get next steps and a free quote within one business day.