AI Summary
Would you like to limit which users can view the list of connected Google Sheets when setting up a Google Sheets connection in WPForms? By default, any user with access to the form builder can see every spreadsheet associated with the connected Google account, which may be a privacy concern on sites with multiple backend users.
This tutorial will show you how to restrict access to the Google Sheets picker using a custom code snippet.
Creating the Snippet
Before we get started, be sure to check out our tutorial on how to add custom code snippets to your site.
The Google Sheets picker loads its data through an AJAX endpoint when a user opens the Google Sheets provider in the form builder. By hooking into the wpforms_providers_settings_builder_ajax_access_token_data_get_google-sheets filter, you can add a permission check before the spreadsheet list is returned.
We’ll cover two common scenarios below.
Restricting Access to Administrators Only
The snippet below limits access to the Google Sheets picker to users with the manage_options capability. By default, this is limited to administrators.
/**
* Restrict the Google Sheets picker to administrators only.
*
* @link https://wpforms.com/developers/
*/
add_filter( 'wpforms_providers_settings_builder_ajax_access_token_data_get_google-sheets', 'wpf_restrict_picker_access_admins_only', 9 );
function wpf_restrict_picker_access_admins_only(): void {
// Restrict access to users with manage_options capability (administrators by default).
if ( ! current_user_can( 'manage_options' ) ) {
wp_send_json_error( 403 );
}
}
Once this snippet is added to your site, any non-administrator who tries to open the Google Sheets picker will receive a 403 error instead of seeing the list of connected spreadsheets. Administrators will continue to see the picker exactly as before.
Restricting Access to a Specific User
If you’d prefer to restrict access to a single user, you can check against a specific user ID instead. This is useful when only one person on your team should be allowed to manage Google Sheets connections.
/**
* Restrict the Google Sheets picker to a specific user.
*
* @link https://wpforms.com/developers/
*/
add_filter( 'wpforms_providers_settings_builder_ajax_access_token_data_get_google-sheets', 'wpf_restrict_picker_access_single_user', 9 );
function wpf_restrict_picker_access_single_user(): void {
// Restrict access to a specific user ID. Replace 1 with the desired user ID.
if ( get_current_user_id() !== 1 ) {
wp_send_json_error( 403 );
}
}
Be sure to replace 1 with the ID of the user you’d like to allow. You can find a user’s ID by going to Users in your WordPress admin and hovering over the user’s name. The ID appears in the URL of the edit link.
That’s it! You’ve successfully restricted access to the Google Sheets picker in WPForms. Would you like to customize other parts of the Google Sheets integration? Take a look at our tutorial on how to set up the Google Sheets addon with WPForms.