Last active
February 13, 2024 04:38
-
-
Save grantambrose/2182669ddc29ab71f948811d6e2b450e to your computer and use it in GitHub Desktop.
Redirect from Woo Product to associated Course (bi-directional field setup)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// this function redirects users to the course they purchased | |
// when they try to access the WooCommerce product that sold the course | |
// as they don't need to see the sales page anymore, they want the lessons | |
add_action( 'template_redirect', 'c_redirect_to_purchased_course' ); | |
function c_redirect_to_purchased_course() { | |
// if it's not a woo product page, return and do nothing | |
if( !is_product() ) return; | |
// get related courses | |
$c_products_related_courses = get_field('c_products_related_courses'); | |
// if no related courses set, return and continue to show the product page | |
if( !$c_products_related_courses ) return; | |
// there is only be one item in array as we limited the field in ACF set to 1 item max | |
// so we can get the first item in array which gives us the ID of the related course | |
$c_products_related_course_id = $c_products_related_courses[0]; | |
// get current wordpress user | |
$current_user = wp_get_current_user(); | |
// if the current wordpress user has purchase the woo product we are trying to load | |
// that sold the online course | |
if ( wc_customer_bought_product( wp_get_current_user()->user_email, get_current_user_id(), get_the_ID() ) ) { | |
// then lets redirect to the URL of the related course | |
wp_redirect( get_permalink($c_products_related_course_id) ); | |
exit; | |
} | |
} | |
// we use the true/false return of this function | |
// to show / hide elements on our course page for people who | |
// have purchased VS have not purchased | |
function c_check_user_access_this_course(){ | |
// if its not a single course, do nothing and stop function | |
if ( ! is_singular('course') ) return false; | |
// always show for admins to help with website management | |
if(current_user_can('administrator')) return true; | |
// get the current wp user | |
$current_user = wp_get_current_user(); | |
// this will always be an array | |
$c_course_related_woo_products = get_field('c_course_related_woo_products'); | |
// if there are related woo products assigned to this course | |
if($c_course_related_woo_products){ | |
if ( wc_customer_bought_product( wp_get_current_user()->user_email, get_current_user_id(), $c_course_related_woo_products[0] ) ) { | |
return true; | |
} | |
} | |
return false; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment