Restricting a User To Only Be Able To Access the Entries of One Specific Gravity Form

Quick Background

Recently I was contacted by a university staff member who needed to access the Gravity Form entries of a specific form on one of our sites.  Though this was a trusted user, they worked outside our Division, so I thought the best thing to do was the following (to ensure they could only access this form’s entries alone):

Steps

  1. First install/active the MemberPress Members plugin.
  2. Clone the “Subscriber” role, naming your cloned role accordingly (in my example, I named it “Student Complaint Users”)
  3. To ensure these users can access the back-end of your site, including Gravity Forms, grant them the following roles using the Members plugin (as appropriate to your situation):
    1. Edit Posts
    2. Edit Other’s Posts
    3. Publish Posts
    4. Read Private Posts
    5. Read
    6. Edit Private Posts
    7. Edit Published Posts
    8. Edit Forms
    9. View Entries
    10. Edit Entries
    11. Delete Entries
  4. Next assign the specific user your newly-created role
  5. Finally, drop the following code in your theme’s functions.php file 

Code

            // function with restricts a user to only be able to access the entries of one Gravity Form alone
function restrict_role_to_singleform() {
    $form_id = '17';
	$login_slug = '/login';
	
	// get current user and see if they have the correct role
	$user = wp_get_current_user();
	if ( !in_array( 'student_complaint_users', (array) $user->roles ) ) 
		return;
	
	// if we made it this far, the user has the "student_complaint_users" role, so get querystring parameters
	$queryStrings = array();
	parse_str($_SERVER['QUERY_STRING'], $queryStrings);
	
	// if they wind up on the main form edit page, redirect them to the specific form entries in question
	if ($queryStrings['page'] == 'gf_edit_forms'){
		wp_redirect( home_url() . '/wp-admin/admin.php?page=gf_entries&id=' . $form_id );
		exit;
	}
	
	// Now check if they aren't in the Gravity Forms entries area (if so, we don't care)?
	if ($queryStrings['page'] != 'gf_entries')
		return;

	// we do want to allow them to view the page showing all forms (eg, /admin.php?page=gf_edit_forms), so if the ID is NOT set, don't do further checks
	if (!isset($_GET['id'])) {
		return;
	}
	else if ($queryStrings['id'] != $form_id) {
		// if we made it this far, they are within Gravity Forms and are trying to view another form's entries
		wp_redirect( home_url() . $login_slug );
		exit;
	}	
}
add_action( 'admin_head', 'restrict_role_to_singleform' );