LMS & eLearning

Snippet: Block LearnDash Course Access Outside Business Hours

Limit when learners can open selected LearnDash courses with a time window checked in the sfwd_lms_has_access filter: site timezone handling, a weekend rule, an on-page notice, caching caveats and tests.

Snippet: Block LearnDash Course Access Outside Business Hours

Some training has to happen on the clock: proctored modules that must be taken during supervised hours, a classroom course that should not be worked on at home, or a client contract that limits platform use to weekdays. LearnDash has start and end dates per course but no concept of a daily window. This snippet adds one using the sfwd_lms_has_access filter from LearnDash 4.18.0.1, with correct timezone handling and a notice on the course page so learners know when to come back.

What the filter gives you

sfwd_lms_has_access( $post_id, $user_id ) in includes/course/ld-course-user-functions.php returns its result through apply_filters( 'sfwd_lms_has_access', $result, $post_id, $user_id ). Because every lesson, topic and quiz check goes through it, a single callback can close an entire course by returning false during the blocked window. The callback must resolve the course with learndash_get_course_id( $post_id ), and it must be fast, since course pages call the function many times.

Time handling done properly

Use the site's timezone from Settings > General rather than the server clock, otherwise a host in another region shifts your window by hours. WordPress exposes it through wp_timezone(), and a DateTimeImmutable built with that timezone gives you the weekday and hour in local time. Avoid date() and current_time( 'timestamp' ), which both have offset pitfalls.

The snippet

<?php
/**
 * Plugin Name: LearnDash business-hours access
 * Description: Closes selected courses outside a daily window and on weekends.
 */

defined( 'ABSPATH' ) || exit;

/**
 * Course ID => window settings.
 * days: ISO weekday numbers, 1 = Monday ... 7 = Sunday.
 * open/close: 24-hour times in the site timezone.
 */
function wwc_timed_courses() {
    return array(
        123 => array(
            'days'  => array( 1, 2, 3, 4, 5 ),
            'open'  => '09:00',
            'close' => '17:30',
        ),
    );
}

/**
 * Whether the course is open right now.
 */
function wwc_course_is_open_now( $course_id ) {
    $rules = wwc_timed_courses();
    if ( ! isset( $rules[ $course_id ] ) ) {
        return true;
    }

    $rule = $rules[ $course_id ];
    $now  = new DateTimeImmutable( 'now', wp_timezone() );

    if ( ! in_array( (int) $now->format( 'N' ), $rule['days'], true ) ) {
        return false;
    }

    $time = $now->format( 'H:i' );

    return ( $time >= $rule['open'] && $time < $rule['close'] );
}

add_filter(
    'sfwd_lms_has_access',
    function ( $has_access, $post_id, $user_id ) {
        if ( ! $has_access ) {
            return $has_access;
        }

        $course_id = (int) learndash_get_course_id( $post_id );
        if ( ! isset( wwc_timed_courses()[ $course_id ] ) ) {
            return $has_access;
        }

        $user_id = (int) $user_id ? (int) $user_id : get_current_user_id();
        if ( learndash_is_admin_user( $user_id ) ) {
            return $has_access;
        }

        return wwc_course_is_open_now( $course_id );
    },
    10,
    3
);

Comparing zero-padded H:i strings works because they sort the same as the times they represent. Windows that cross midnight need a different comparison; swap the last line for a check that the time is after the opening or before the closing time when close is smaller than open.

Showing the schedule on the course page

A learner who lands on a closed course sees locked steps and the enrollment box, which looks like a bug. Print the schedule with the learndash-course-before action, which the ld30 course template fires with the post ID, course ID and user ID:

<?php
add_action(
    'learndash-course-before',
    function ( $post_id, $course_id, $user_id ) {
        $rules = wwc_timed_courses();
        if ( ! isset( $rules[ (int) $course_id ] ) || wwc_course_is_open_now( (int) $course_id ) ) {
            return;
        }

        $rule = $rules[ (int) $course_id ];

        printf(
            '<div class="ld-alert ld-alert-warning">%1$s</div>',
            esc_html(
                sprintf(
                    /* translators: 1: opening time, 2: closing time */
                    __( 'This course is available Monday to Friday between %1$s and %2$s. Please come back during those hours.', 'wwc' ),
                    $rule['open'],
                    $rule['close']
                )
            )
        );
    },
    10,
    3
);

Keep the wording in step with the days array; if you change the schedule often, build the sentence from the array instead of hard-coding "Monday to Friday".

What happens to a learner mid-lesson

Access is evaluated per request, so a learner reading a lesson at closing time keeps the page they already loaded. The next click, including Mark Complete, is refused and they land on the course page with the notice. Quiz attempts in progress are the awkward case: the quiz runs in the browser and submits at the end, and the submission is processed by an AJAX request that does not re-check access the same way. If quizzes must stop at closing time, set the quiz's own time limit so that it cannot run past the window, which is a setting rather than code.

Per-group windows

Sites that run the same course for several client organisations often need a different window per group rather than per course. The filter still works; the rule lookup changes. learndash_get_users_group_ids( $user_id ) returns the IDs of the groups a learner belongs to, so the rule map can be keyed by group ID instead, and the callback checks whether any of the learner's groups has a rule that is currently closed. Store the rule on the group itself as post meta, for example wwc_access_window holding the days, open and close values, so an administrator can edit it on the group screen with a small meta box rather than in code. Because learndash_get_users_group_ids() caches its result for the request, calling it inside the filter is acceptable, but resolve it once per request into a static variable if the course page is slow on large sites.

Holidays follow the same pattern. Keep an array of dates in the site timezone, check $now->format( 'Y-m-d' ) against it before the weekday test, and close the course on those days regardless of the hour. A yearly review of that array is the only maintenance it needs.

Logging refused attempts

When learners complain that the course "did not work", a record of refused requests settles it quickly. Inside the callback, when it is about to return false, call do_action( 'wwc_timed_access_refused', $course_id, $user_id ) and attach a logger to that action in a separate file. Keeping the logging out of the access callback means the rule stays readable and the log can be switched off without touching it. Write to a custom table or a transient-based counter rather than error_log(), which fills server logs fast on a busy site.

Caching

A full-page cache can serve an "open" page after closing time. Course pages for logged-in users are normally excluded by the cache plugin's logged-in rule, and open courses viewed by visitors should not be timed in the first place, so in practice this rarely bites. If you use a CDN that caches logged-in pages, add a cache lifetime shorter than the gap between your boundaries or exclude the course URLs.

Testing without waiting for Friday

Temporarily set the window to a few minutes either side of the current time, load a lesson as a non-admin learner, wait for the closing minute and reload. Then change the site timezone in Settings > General by one hour and confirm the behaviour shifts with it. Restore both settings afterwards. Administrators bypass the rule, so test with a subscriber account.

The same filter restricts by role, as shown in our role restriction snippet, and the two callbacks can coexist because each only turns a yes into a no. For dates rather than daily windows, use the course's own start and end dates, explained in course start and end dates. For lesson release schedules, the drip filters are the right layer; see the drip filters guide.

When to get help

Per-course windows are a quick addition. Per-group schedules, holiday calendars, or a settings page for training coordinators are small plugin projects, and our LearnDash services team builds them regularly. A LearnDash developer can also confirm how your quiz settings interact with the window before a proctored exam goes live.

Frequently asked questions

Does LearnDash have a built-in business-hours setting?

No. Courses have start and end dates and lessons have drip schedules, but there is no daily or weekly window, which is why this snippet uses the access filter.

Which timezone does the snippet use?

The site timezone from Settings > General, via wp_timezone(). Server time and per-user timezones are ignored.

Can a learner finish a quiz that started before closing time?

Usually yes, because the quiz submits at the end. Use the quiz time limit to keep attempts inside the window.

Are administrators affected?

No. The callback returns early for learndash_is_admin_user() so staff can maintain courses at any time.

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.