Search code examples
wordpressgoogle-sheetsgoogle-apigoogle-sheets-apininja-forms

Display list of elements from google sheets in drop down select menu in Wordpress Form built by Ninja Forms


So I am trying to manipulate the functions.php file in Wordpress to add a function that will make an API call to Google Sheets API using OAUth 2.0 or API key (whichever is more secure), get the list of elements in a column and store it in an array $options which will then be displayed as a drop down menu list.

To do Select field pre-population with Ninja Forms, I referred https://francescocarlucci.com/wordpress/select-field-pre-population-ninja-forms/ The $options is an array which when set statically gives me the expected dropdown menu: e.g. -

$options[1]['label'] = "One";
$options[2]['label'] = "Two";
$options[3]['label'] = "Three"; 

I have tried the OAuth 2.0 method from https://developers.google.com/sheets/api/quickstart/php

In the line $client->setAuthConfig( '/credentials.json' ); the code cannot access the file credentials.json. I did add the JSON file and all other relevant API files in the same folder as functions.php. Also I need a way to automate the

I want the list of elements to be displayed in Wordpress dropdown. Instead, I am getting a blank Page and the below stack trace in my debug.log file:

[09-Jul-2019 19:46:15 UTC] PHP Fatal error:  Uncaught InvalidArgumentException: file "/credentials.json" does not exist in /var/www/html/wp-content/themes/twentynineteen/vendor/google/apiclient/src/Google/Client.php:870
#0 /var/www/html/wp-content/themes/twentynineteen/functions.php(322): 
Google_Client->setAuthConfig('/credentials.js...')
#1 /var/www/html/wp-content/themes/twentynineteen/functions.php(371): getClient()
#2 /var/www/html/wp-content/themes/twentynineteen/functions.php(437): quickstart()
#3 /var/www/html/wp-includes/class-wp-hook.php(286): select_pre_population_callback(Array, Array)
#4 /var/www/html/wp-includes/plugin.php(208): WP_Hook->apply_filters(Array, Array)
#5 /var/www/html/wp-content/plugins/ninja-forms/includes/Display/Render.php(271): apply_filters('ninja_forms_ren...', Array, Array)
#6 /var/www/html/wp-content/plugins/ninja-forms/includes/Display/Render.php(400): NF_Display_Render::localize(1)
#7 /var/www/html/wp-content/plugins/ninja-forms/ninja-forms.php(935): NF_Display_Render::localize_preview('1')
#8 /var/www/h in /var/www/html/wp-content/themes/twentynineteen/vendor/google/apiclient/src/Google/Client.php on line 870

Solution

  • The comment by @cabrerahector worked for me.

    PHP is telling that it can't find credentials.json file. Tried this instead: $client->setAuthConfig( get_theme_file_path('credentials.json')