Skip to content

Instantly share code, notes, and snippets.

@j2machado
Last active May 3, 2022 17:57
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save j2machado/c45e979fca472e8cab2520ec0dce195a to your computer and use it in GitHub Desktop.
Save j2machado/c45e979fca472e8cab2520ec0dce195a to your computer and use it in GitHub Desktop.
LearnDash - In a course with Closed Access Mode, redirect the unenrolled users to the Button URL value, e.g. a WooCommerce Product or a Landing Page to purchase the course
<?php
/* In LearnDash, prevent unenrolled users from reaching
the single course page and redirect them to the Button URL value */
/* TO DO
* - Add support for groups
* - Add an option in LearnDash settings to turn on/off.
* - Add support for externa URLs as well (Unbounce, Click Funnels, etc).
*/
add_action('template_redirect', function(){
//If current user is admin, exit
if(current_user_can( 'manage_options' ) ){
return;
}
//Check if current post is not a course
if("sfwd-courses" != get_post_type()){
return;
}
//Get the course options
$courseOptionsSerialized = get_post_meta(get_the_ID(), '_sfwd-courses', true);
//Get the Button URL value
$courseProductURL = $courseOptionsSerialized['sfwd-courses_custom_button_url'];
//Get the Course Access Mode
$courseAccessMode = $courseOptionsSerialized['sfwd-courses_course_price_type'];
//Check if the course access mode is set to closed
if($courseAccessMode != "closed"){
return;
}
//Check if the product URL is not empty
if($courseProductURL == ""){
return;
}
//Check if the current user is enrolled in the current course
if( ld_course_check_user_access( get_the_ID() , get_current_user_ID() )){
return;
}
//Redirect the user to the page in Button URL
wp_safe_redirect( $courseProductURL );
exit;
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment