iamcanadian1973
9/18/2018 - 12:40 AM

learndash-filter-courses-by-group.php

<?php

// Add group custom group attribute to check later
add_filter( 'ld_course_list_shortcode_attr_defaults', function( $defaults ) {
    
    $defaults['mygroups'] = null;
    return $defaults;
    
}, 10 );

// Filter course list by group id
add_filter('learndash_ld_course_list_query_args', function( $filter, $atts ) {
        
    if ( ! is_user_logged_in() || ! $atts['mygroups'] ) {
        return $filter;
    }
    
    $user_id = get_current_user_id();
    $group_ids = learndash_get_users_group_ids( $user_id );
    $group_meta_id = [];
    
    if( empty( $group_ids ) ) {
        return $filter;
    }
    $meta_query = [];
    
    $meta_query[] = [ 'relation' => 'OR' ];
    
    foreach( $group_ids as $group_id) {
        
        $group_meta_key = sprintf( 'learndash_group_enrolled_%d', $group_id ); 
        
        $meta_query[] = array(
					'key' => $group_meta_key,
					'compare' => 'EXISTS'
				);
    }
    
    $filter['meta_query'] = $meta_query;
    
    return $filter;
}, 10, 2);