Filter uncanny-learndash-groups

ulgm_rest_api_callback_roles

Filters the roles accessible via the REST API, allowing customization of permitted user roles.

add_filter( 'ulgm_rest_api_callback_roles', $callback, 10, 1 );

Description

Filters the list of allowed user roles that can access specific Uncanny Groups REST API endpoints. Developers can modify this array to grant access to custom roles or restrict access from default roles.


Usage

add_filter( 'ulgm_rest_api_callback_roles', 'your_function_name', 10, 1 );

Return Value

The filtered value.


Examples

// Example function to modify the allowed roles for the REST API callback.
// This could be used to allow specific custom roles to access certain REST API endpoints.
add_filter( 'ulgm_rest_api_callback_roles', 'my_custom_ulgm_rest_api_roles', 10, 1 );

/**
 * Modifies the default allowed roles for the Uncanny LearnDash Groups REST API.
 *
 * By default, 'administrator', 'group_leader', and 'super_admin' are allowed.
 * This function adds 'custom_group_manager' and 'lesson_reviewer' to the list
 * of allowed roles.
 *
 * @param array $default_roles The array of default roles.
 * @return array The modified array of allowed roles.
 */
function my_custom_ulgm_rest_api_roles( $default_roles ) {
	// Add a custom role that might be used for managing groups in a specific context.
	$default_roles[] = 'custom_group_manager';

	// Add another custom role that might be allowed to review lesson progress via the API.
	$default_roles[] = 'lesson_reviewer';

	// You could also conditionally remove roles if needed, e.g.:
	// $key_to_remove = array_search( 'group_leader', $default_roles );
	// if ( $key_to_remove !== false ) {
	//     unset( $default_roles[ $key_to_remove ] );
	// }

	return $default_roles;
}

Placement

This code should be placed in the functions.php file of your active theme, a custom plugin, or using a code snippets plugin.


Source Code

src/classes/admin/class-admin-rest-api.php:84
src/classes/helpers/rest-api-end-points.php:326
src/classes/helpers/rest-api-end-points.php:632

public function permission_callback_check( $admin_only = false ) {
		if ( ! is_user_logged_in() ) {
			return new WP_Error( 'ulgm_rest_cannot_view', __( 'Sorry, you cannot view this resource.', 'uncanny-learndash-groups' ), array( 'status' => rest_authorization_required_code() ) );
		}

		if ( $admin_only ) {
			return current_user_can( 'manage_options' );
		}

		$user          = wp_get_current_user();
		$allowed_roles = apply_filters(
			'ulgm_rest_api_callback_roles',
			array(
				'administrator',
				'group_leader',
				'super_admin',
			)
		);
		if ( array_intersect( $allowed_roles, $user->roles ) ) {
			return true;
		}

		return new WP_Error( 'ulgm_rest_cannot_view', __( 'Sorry, you cannot view this resource.', 'uncanny-learndash-groups' ), array( 'status' => rest_authorization_required_code() ) );
	}

Scroll to Top