David Stockdale's Scrapcode

Hiding WordPress Theme API Keys in GitHub

Now if your like me you know just enough about GitHub to know that you can hide things with gitignore.

But that leads you to the question: how do I hide things in important files like “function.php”?

You can’t ignore the whole file just to hide one little API Key right?

Right.

But you can put your API Keys somewhere else, hide that file and then reference it in your functions!

Config

First create a PHP file in your child theme (I called mine “config.php” but you can call it what you like).

Then put your API Keys in here like this:

<?php
 $api_key1 = "YOUR KEY HERE";

This will be the file that you can hide with gitignore.

Function

Now in your “functions.php” you will need to require that file once (outside of your actual functions):

require_once('config.php');

Now within whatever function you use the API Key within you need to declare the variable as a global variable:

global $api_key1;

Then simply echo that global variable:

echo $api_key1;

Example

Here’s an example of me doing all of this in one function:

require_once('config.php');
add_shortcode( 'wp_google_search', 'search_attempt' );
function search_attempt(){
global $api_key1;
?>
<div class="thing">
	<div class="uk-container uk-container-center">
		<script async src="https://cse.google.com/cse.js?cx=<?php echo $api_key1; ?>"></script>
		<div class="gcse-search"></div>
	</div>
</div>
<?php
}

Leave a Reply