Find out in this tutorial how to save the Google API key in the WordPress database and get it for use with Advanced Custom Fields.
In previous tutorials you have seen how to perform advanced customizations with the Advanced Custom Fields map field thanks to the Google API.
In order to take advantage of it you have to get the API key and then add it via a filter to Advanced Custom Fields. According to its own documentation, like this:
function my_acf_google_map_api( $api ){
$api['key'] = 'xxx'; return $api;
}
add_filter('acf/fields/google_map/api', 'my_acf_google_map_api');
This option is perfectly valid, but I’m not a big fan of leaving the API key exposed in a file (in this case functions.php or a functionality plugin).
So I prefer to store the key in the database and then get it from there. This way it is a little less accessible.
Let’s see how to do it.
Code to save the Google API key in the database and use it in Advanced Custom Fields
Remember that first you have to get an API key from Google.
Then, add the following code at the end of functions.php or in your functionality plugin:
To see this and another 1097 code snippets of this website, login or subscribe here.
With this code you use the add_option
function to store the key in the database. Just replace xxx with your API key.
As it is hooked in the init
hook, you only have to load or refresh the web once for it to be executed. Once you have done this it will be saved, so you can and should delete this snippet.
Once you have the key in the database you just need to use the ACF filter by calling it with a get_option
.
To do this add the following snippet to your functions.php file or your functionality plugin:
To see this and another 1097 code snippets of this website, login or subscribe here.
Done.
As you can see in this case you do not expose the key and add a degree of security to prevent misuse.
Conclusions
Now you know how to save an API key in the database and then use it in Advanced Custom Fields.
By the way, this example is intended for the use of the Google API key with Advanced Custom Fields, but you can use the same strategy for any other plugin that uses a similar system.
Any questions? I read you in the comments.
And if you want to give me any suggestion for future tutorials, leave it in the contact form. Advantages of being a subscriber. 😉