How to Password Protect LearnDash Courses

Requirements:

Step 1: Once activating our plugins, navigate to Password Protect WordPress >> Settings from your admin dashboard.

Then select “Courses”, “Lessons”, “Topics” and other LearnDash post types under Post Type Protection option.

Step 2: Password protect a course page.

Simply hover the course title and then click on “Protect” button to lock its content immediately.

Step 3: There are 2 options to protect LearnDash lessons and topics once the course page is protected.

To do so, add the corresponding code snippet into your (child) theme’s functions.php file.

Show password form in Lesson and Topic pages

add_filter(
    'the_content',
    function ($content) {
        if (!function_exists('ppw_core_render_login_form')) {
            return $content;
        }
        $post_type = get_post_type();
        if ('sfwd-lessons' !== $post_type && 'sfwd-topic' !== $post_type) {
            return $content;
        }

        $course_id = learndash_get_course_id();
        if (!post_password_required($course_id)) {
            return $content;
        }
        global $post;
        $post_id = $post->ID;
        $post->ID = $course_id;
        $form = ppw_core_render_login_form();
        $post->ID = $post_id;

        return $form;
    },
    100
);

Redirect users to Course page

add_action(
    'template_redirect',
    function () {
        if (!function_exists('ppw_core_render_login_form')) {
            return;
        }
        $post_type = get_post_type();
        if ('sfwd-lessons' !== $post_type && 'sfwd-topic' !== $post_type) {
            return;
        }

        $course_id = learndash_get_course_id();
        if (!post_password_required($course_id)) {
            return;
        }

        wp_redirect(get_post_permalink($course_id));
        exit;
    },
    100
);
Lasted updated on February 20, 2021