LMS & eLearning

Building a Custom LearnDash REST API Controller Under ldlms/v2

How LearnDash loads its REST controllers, how the learndash-rest-api-controllers filter lets you add, replace or remove one, and two worked controllers: a report route and a post type route on the v2 base class.

Building a Custom LearnDash REST API Controller Under ldlms/v2

When the built-in routes do not fit, you have two options: register a route in your own namespace with register_rest_route(), which always works, or plug a controller into LearnDash's own loader so that it lives under ldlms/v2, respects the renamed bases from settings, and inherits the permission and query behaviour of LearnDash's base controller. The second option is what this guide covers. It explains how LearnDash 4.18.0.1 loads its controllers, how the filter that exposes that list works, and then builds two controllers: a read-only report endpoint on WP_REST_Controller and a post type endpoint on LD_REST_Posts_Controller_V2.

How LearnDash loads controllers

The LearnDash_REST_API singleton hooks rest_api_init. When the API is enabled it builds an associative array of controller class names, each mapped to an array with two keys: file, the absolute path of the class file, and register_routes, a boolean. Ten v1 entries and twenty-nine v2 entries are listed, from LD_REST_Courses_Controller_V2 through LD_REST_Quiz_Statistics_Controller_V2. The array then passes through apply_filters( 'learndash-rest-api-controllers', $controllers ), and for each entry the loader includes the file if it exists and, when register_routes is true, instantiates the class with no constructor arguments and calls its register_routes() method, storing the instance as a property named after the class. The hyphens in the filter name are deliberate and marked with a phpcs ignore in source, so copy the name exactly.

Three things follow. You can add a controller by appending an entry with your own file path. You can replace a built-in controller by pointing its entry's file at your file, provided your file defines a class of the same name, since the loader uses the key as the class to instantiate. And you can switch a controller off by setting register_routes to false or unsetting the entry, which is a cleaner way to hide, say, the echo helper than blocking the route elsewhere. Our securing guide uses that last trick.

Registering your controller

<?php
add_filter(
    'learndash-rest-api-controllers',
    function ( $controllers ) {
        $controllers['Acme_LD_REST_Completions_Controller'] = array(
            'register_routes' => true,
            'file'            => plugin_dir_path( __FILE__ ) . 'includes/class-acme-ld-rest-completions-controller.php',
        );

        return $controllers;
    }
);

Because the loader instantiates with new $controller_class(), your constructor must accept no required arguments. Because it runs during LearnDash's rest_api_init, all LearnDash functions are available.

Controller one: a completions report on WP_REST_Controller

LearnDash's helper controllers, such as price types and progress status, extend plain WP_REST_Controller and set $namespace to ldlms/v2 themselves. That is the right base for a resource that is not a post type. The following controller returns, for one course, the users who completed it and when, reading the course_completed_{id} user meta that LearnDash writes on completion.

<?php
class Acme_LD_REST_Completions_Controller extends WP_REST_Controller {

    public function __construct() {
        $this->namespace = trailingslashit( LEARNDASH_REST_API_NAMESPACE ) . 'v2';
        $this->rest_base = 'reports/completions';
    }

    public function register_routes() {
        register_rest_route(
            $this->namespace,
            '/' . $this->rest_base . '/(?P<course>[\d]+)',
            array(
                'args' => array(
                    'course' => array( 'type' => 'integer', 'required' => true ),
                ),
                array(
                    'methods'             => WP_REST_Server::READABLE,
                    'callback'            => array( $this, 'get_items' ),
                    'permission_callback' => array( $this, 'get_items_permissions_check' ),
                    'args'                => $this->get_collection_params(),
                ),
                'schema' => array( $this, 'get_public_item_schema' ),
            )
        );
    }

    public function get_items_permissions_check( $request ) {
        if ( learndash_is_admin_user() ) {
            return true;
        }
        if ( learndash_is_group_leader_user() ) {
            $courses = learndash_get_groups_administrators_courses( get_current_user_id() );
            if ( in_array( (int) $request['course'], array_map( 'intval', (array) $courses ), true ) ) {
                return true;
            }
        }
        return new WP_Error( 'ld_rest_cannot_view', 'Sorry, you are not allowed to view this item.', array( 'status' => rest_authorization_required_code() ) );
    }

    public function get_items( $request ) {
        $course_id = (int) $request['course'];
        if ( learndash_get_post_type_slug( 'course' ) !== get_post_type( $course_id ) ) {
            return new WP_Error( 'rest_post_invalid_id', 'Invalid course ID.', array( 'status' => 404 ) );
        }

        $query = new WP_User_Query(
            array(
                'meta_key'     => 'course_completed_' . $course_id,
                'meta_compare' => 'EXISTS',
                'number'       => (int) $request['per_page'],
                'paged'        => (int) $request['page'],
                'fields'       => array( 'ID', 'display_name' ),
            )
        );

        $items = array();
        foreach ( $query->get_results() as $user ) {
            $items[] = array(
                'user'         => (int) $user->ID,
                'name'         => $user->display_name,
                'completed_on' => gmdate( 'c', (int) get_user_meta( $user->ID, 'course_completed_' . $course_id, true ) ),
            );
        }

        $response = rest_ensure_response( $items );
        $response->header( 'X-WP-Total', (int) $query->get_total() );
        $response->header( 'X-WP-TotalPages', (int) ceil( $query->get_total() / max( 1, (int) $request['per_page'] ) ) );
        return $response;
    }

    public function get_item_schema() {
        return array(
            '$schema'    => 'http://json-schema.org/draft-04/schema#',
            'title'      => 'completion',
            'type'       => 'object',
            'properties' => array(
                'user'         => array( 'type' => 'integer', 'context' => array( 'view' ) ),
                'name'         => array( 'type' => 'string', 'context' => array( 'view' ) ),
                'completed_on' => array( 'type' => 'string', 'format' => 'date-time', 'context' => array( 'view' ) ),
            ),
        );
    }
}

The permission callback mirrors LearnDash's own pattern: administrators everywhere, group leaders only for courses in their groups, everyone else refused with the same error code LearnDash uses. get_collection_params() from the parent supplies page, per_page and search. For heavier reports, read the activity table described in our database tables guide instead of user meta.

Controller two: a post type on the v2 base class

If your resource is a post type that behaves like a LearnDash step, for example a custom "resource" post type attached to courses, extend LD_REST_Posts_Controller_V2. Its constructor takes the post type, sets the namespace from LEARNDASH_REST_API_NAMESPACE and the $version property, and hooks rest_{post_type}_query, rest_prepare_{post_type}, rest_pre_insert_{post_type} and rest_after_insert_{post_type} to its own filter methods. register_routes() then registers the collection and single routes according to the $route_methods_collection and $route_methods_singular arrays, which default to read and create for the collection and read, update and delete for the single item, wiring each to the standard permission methods. The post type must have show_in_rest true and a rest_controller_class is not required, because LearnDash instantiates the controller directly.

<?php
class Acme_LD_REST_Resources_Controller extends LD_REST_Posts_Controller_V2 {

    public function __construct( $post_type = 'acme-resource' ) {
        parent::__construct( $post_type );
        // No settings field exists for a custom slug, so pass the default base.
        $this->rest_base = $this->get_rest_base( 'resources', 'resources' );
        // Read-only for API clients.
        $this->route_methods_collection = array( WP_REST_Server::READABLE );
        $this->route_methods_singular   = array( WP_REST_Server::READABLE );
    }

    protected function register_fields() {
        register_rest_field(
            $this->post_type,
            'course',
            array(
                'get_callback' => function ( $post_data ) {
                    return (int) get_post_meta( $post_data['id'], 'course_id', true );
                },
                'schema'       => array( 'type' => 'integer', 'context' => array( 'view', 'edit' ) ),
            )
        );
        do_action( 'learndash_rest_register_fields', $this->post_type, $this );
    }

    public function get_items_permissions_check( $request ) {
        $allowed = parent::get_items_permissions_check( $request );
        if ( true !== $allowed || learndash_is_admin_user() ) {
            return $allowed;
        }
        $course_id = (int) $request['course'];
        if ( empty( $course_id ) || ! sfwd_lms_has_access( $course_id ) ) {
            return new WP_Error( 'ld_rest_cannot_view', 'Sorry, you are not allowed to view this item.', array( 'status' => rest_authorization_required_code() ) );
        }
        return true;
    }

    public function rest_query_filter( $query_args, $request ) {
        if ( ! $this->is_rest_request( $request ) ) {
            return $query_args;
        }
        $query_args = parent::rest_query_filter( $query_args, $request );
        if ( ! empty( $request['course'] ) ) {
            $query_args['meta_key']   = 'course_id';
            $query_args['meta_value'] = (int) $request['course'];
        }
        return $query_args;
    }
}

Two base class details matter here. get_rest_base() appends _v2 to the slug and reads it from the REST API settings section, returning your second argument when no such setting exists, so built-in slugs stay renameable and yours has a fixed default. And is_rest_request() guards the query filter so that it does not alter non-REST queries for the same post type, which is the mistake that breaks admin lists when people hook rest_{post_type}_query without it. Firing learndash_rest_register_fields from your own register_fields() keeps the extension point documented in our custom fields guide working for other plugins.

Testing

Request /wp-json/ldlms/v2 and confirm your routes are listed with their schemas, then test each permission branch with an administrator, a group leader and a learner using application passwords. The echo helper route, documented with the other helper endpoints, is handy for confirming which user a client is authenticating as before you blame your permission code.

When to get help

A report route is a day with the pattern above. A full custom resource with create and update support, schema validation, group leader scoping and backward compatibility across LearnDash upgrades is a development project; our LearnDash services team and LearnDash development practice build those, and a LearnDash developer can also review a controller before it is exposed to partners.

Frequently asked questions

Which filter adds a controller to the LearnDash REST API?

The hyphenated learndash-rest-api-controllers filter. Append an entry keyed by class name with a file path and register_routes true; LearnDash includes the file, instantiates the class and calls register_routes().

Can I replace a built-in controller?

Yes. Point the existing entry's file at your own file that defines a class of the same name. Keep the class loaded only through the filter so the original file is never included.

Do I have to extend a LearnDash class?

No. Plain WP_REST_Controller with the ldlms/v2 namespace is what LearnDash's helper controllers use. Extend LD_REST_Posts_Controller_V2 only for post type resources that should inherit its query and field behaviour.

Why does my route not appear?

The API is disabled through the constant or filter, the file path does not exist so the loader skipped it, or register_routes is false. Check /wp-json/ldlms/v2 for the route list.

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.

Free consultation

Need help with LearnDash?

Tell us what you are working on. A developer who does this every week reads your message and replies within one business day with next steps and a free quote.

  • Free consultation and quote
  • NDA on request
  • You own the source code
  • Reply within one business day

Tell us about your project

Add budget and timeline optional, helps us quote faster

This form is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.

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.