Browse: Home / Snippets /

Enroll user in all free courses upon registration

Contents


Snippet #

add_action( 'user_register', function( $user_id ) {

	// Args for all courses
	$course_args = [
		'post_type'  => 'sfwd-courses',
		
		// Please be careful with unbounded queries
		// This is not going to work well if you have a lot of courses
		// Test on a staging/dev server first!
		'posts_per_page'  => -1,
	];
	
	// Query all courses
	$course_query = new WP_Query( $course_args );
	
	// Check if there are courses
	if ( $course_query->have_posts() ) :
	
		// Get the free course ID array started
		$free_course_ids = [];
	
		while ( $course_query->have_posts() ) :
			$course_query->the_post();
			
			$meta = get_post_meta( get_the_ID(), '_sfwd-courses', true );
		
			// Add free course ID to the array
			if ( 'free' === $meta['sfwd-courses_course_price_type'] ) :
				$free_course_ids[] = get_the_ID();
			endif;
			
		endwhile;
	
		// Check if there are any free courses
		if ( ! empty( $free_course_ids ) ) :
			
			// Related snippet: https://developers.learndash.com/snippet/enroll-new-user-into-multiple-courses-on-registration/
			foreach ( $free_course_ids as $course_id ) :
				ld_update_course_access( $user_id, $course_id, $remove = false );
			endforeach;
	
		else :

			// Stop if there are no free courses
			return;
	
		endif;
	
	else :
	
		// Stop if there are no courses
		return;
	
	endif;

});