On the Google developer API page, it talks briefly on retrieving a dynamic list of fonts using JSON/JavaScript.
I was wondering how would I be able to pull the web fonts API into my WordPress theme so that I’m not creating my own list or have to constantly release an update of fonts.
Thank you.
Here is some quick first draft code for populating a dropdown from the Google Font API, I do not know about the options framework so this will not deal with that.
1. Get an API Access Key from Google
Your request will need a valid key, you can follow the instruction here on how to get one:
https://developers.google.com/webfonts/docs/developer_api
It’s free for a certain request # per day and you also get some cool usage stats with it.
2. Let’s use WordPress’s HTTP API to get the JSON response
Notice
'sslverify' => false
, this is because Google requires SSL to authorize the API key, you can remove this and it might work, but if you get an SSL verification error (esp on localhost) you can try and set it to false.3. Loop through the response
Now we have something to work with so let’s check for errors and loop through the data that Google returns.
The above simply returns the font family, but there is a lot more data returned via the Googsy, for example the font-weight choice and also a bunch of font subsets, I have left that out to keep this example simple. Also you probably should use javascript instead of PHP, but let’s not deal with that (you can enqueue
wp-includes/js/json2.js
).4. Output
Now we have a list fonts of which are output in a loop via
$str
, you could add them to a input box with something like<option value="<?php echo $str; ?>"><?php echo $str; ?></option>;
, yes it’s kinda of ghetto but it will look like:You probably want to put that info inside one of the option frameworks fields or something.
5. Now we need to actually get the font we select
Since we set the input value to the fonts name that is more or less all Googsy wants, well kinda, that part above where I eliminated font subsets and weights will cause some issues, so you will need to extend that loop to include the data you want!
So now we make the dropdown select grabs the input and append it to the CSS Google API url, which look like
http://fonts.googleapis.com/css?family= ..your font name +stuff ....
For example: http://fonts.googleapis.com/css?family=Anonymous+Pro
There are a lot of things I did not go over here such as storing the values using the Transients_API because Google updates the font collection often and we don’t need to keep pounding them for the same info.
Also using some build in function like wp_list_pluck to pick your fonts out of the list.
ps. I didn’t finish the code for part 5 because I’m hungry so hopefully this sets you on the right track.