How to add Google Web Fonts with Font Preview in WordPress without Plugins

google-web-fonts-with-preview

Unlike the usual and most common use fonts like Arial, Verdana, Tahoma and Helvetica. Google Web Fonts are more beautiful, readable, accessible and modern. Google Fonts makes it quick and easy for everyone to use web fonts, including professional designers and developers.

There’s already a tons of Google Web Fonts WordPress plugins out there like WP Google Fonts, Google Fonts Manager and Google Web Font for WordPress. There’s also a paid premium Google Web Fonts WordPress Plugin such as Ultimate Google Web Fonts but today i am going to show you an easy step by step on ‘How to add Google Web Fonts with Font Preview in WordPress without Plugins’.

I will be creating a Google web fonts options panel with font preview in WordPress dashboard menu. First thing you need to do is create a blank PHP and name it gwf-options.php and upload it to your current theme root. wp-content/themes/current-theme/gwf-options.php

After that, open your functions.php and add this line of code at the bottom of the php before closing ?>

include( get_template_directory() . '/gwf-options.php');

that’s easy right?, and now we will begin the more important part of the tutorial.

Step 1 – Create the menu and sub-menu page

We will be creating a menu and sub-menu for the GWF options. GWF setting page for the fonts option selection with font preview and the other are the GWF update page for the Google web fonts list update.

Start by adding below code into the newly created gwf-options.php

///////////////////////////////////////////////////////////////////////
// Create the Google Web Fonts Dashboard Menu
///////////////////////////////////////////////////////////////////////
function register_google_webfonts_menu(){
/* add main menu for GWF */
add_menu_page( 'Google Web Fonts', 'GW Fonts', 'manage_options', 'google-fonts-settings', 'wp_gwf_fonts_settings', get_template_directory_uri() . '/google.png' , 100 );

/* add sub menu - settings for GWF */
add_submenu_page('google-fonts-settings', 'GWF Settings', 'GWF Settings Page', 'manage_options', 'google-fonts-settings', 'wp_gwf_fonts_settings');

/* add sub menu - updates for GWF */
add_submenu_page('google-fonts-settings', 'GWF Update', 'GWF Update Page', 'manage_options', 'google-fonts-update', 'wp_gwf_fonts_update');

}
add_action( 'admin_menu', 'register_google_webfonts_menu' );

as you can see there’s 2 functions ( wp_gwf_fonts_settings() and wp_gwf_fonts_update() ) needed to create to prevent any warning error function not found notice which i will cover in later part of the tutorial.

You can download the admin menu icon google.png here.

Step 2 – Create a function to fetch Google web fonts family list

We will be using this function to get a list of available Google web fonts family list in array to be added to options selection later on.

///////////////////////////////////////////////////////////////////////
// Fetch the Google Web Fonts API list
///////////////////////////////////////////////////////////////////////
if( !function_exists('wp_get_google_webfonts_list') ):
function wp_get_google_webfonts_list($key='', $sort='') {
    /*
    $key = Web Fonts Developer API
    $sort=
    alpha: Sort the list alphabetically
    date: Sort the list by date added (most recent font added or updated first)
    popularity: Sort the list by popularity (most popular family first)
    style: Sort the list by number of styles available (family with most styles first)
    trending: Sort the list by families seeing growth in usage (family seeing the most growth first)
    */

$http = (!empty($_SERVER['HTTPS'])) ? "https" : "http";

$google_api_url = 'https://www.googleapis.com/webfonts/v1/webfonts?key=' . $key . '&sort=' . $sort;
//lets fetch it
$response = wp_remote_retrieve_body( wp_remote_get($google_api_url, array('sslverify' => false )));
if( is_wp_error( $response ) ) {
} else {
$data = json_decode($response, true);
$items = $data['items'];
foreach ($items as $item) {
$font_list[] .= $item['family'];
}
}
//Return the saved lit of Google Web Fonts
return $font_list;
}
endif;

Step 3 – Preparing wp_gwf_fonts_settings()

Just as mention in step 1, There are two functions need to be created for the menu and sub-menu panel. Here we will be creating the setting page for the GWF options. First we need to add a global variable to used later in other functions.

////////////////////////////////////////////////////////////////////
// Create the settings page for GWF
/////////////////////////////////////////////////////////////////////////

// this will store the google web font family list
$get_font_transiet = get_transient( 'wp_gwf_list_save' );

// the setting input for GWF options
$gwf_options = array (

array(
"header-title" => __("Google Web Fonts Settings", TEMPLATE_DOMAIN),
"name" => __("Body Font", TEMPLATE_DOMAIN),
	"description" => __("Choose a font for the body text.", TEMPLATE_DOMAIN),
	"id" => "_body_font",
	"type" => "select",
	"options" => $get_font_transiet,
	"default" => ""),

array(
"name" => __("Headline Font", TEMPLATE_DOMAIN),
	"description" => __("Choose a font for the headline h1,h2,h3,h4,h5,h6 text.", TEMPLATE_DOMAIN),
	"id" => "_headline_font",
	"type" => "select",
	"options" => $get_font_transiet,
	"default" => ""),

);

and now adding the wp_gwf_fonts_settings()

function wp_gwf_fonts_settings() {
global $get_font_transiet, $gwf_options;
if ( $_GET['page'] == 'google-fonts-settings' ) {

if ( 'save' == $_REQUEST['action'] ) {
foreach ($gwf_options as $value) {
update_option( $value['id'], $_REQUEST[ $value['id'] ] );
}
foreach ($gwf_options as $value) {
if( isset( $_REQUEST[ $value['id'] ] ) ) { update_option( $value['id'],  $_REQUEST[ $value['id'] ] ); } else { delete_option( $value['id'] ); }
}

echo "<SCRIPT LANGUAGE='JavaScript'>
window.location='". admin_url('/'). "admin.php?page=google-fonts-settings&saved=true" . "';
</script>";

} else if( 'reset' == $_REQUEST['action'] ) {

foreach ($gwf_options as $value) {
delete_option( $value['id'] );
}

echo "<SCRIPT LANGUAGE='JavaScript'>
window.location='". admin_url('/'). "admin.php?page=google-fonts-settings&reset=true" . "';
</script>";

}

}
?>

<div id="custom-theme-option" class="wrap">
<?php screen_icon('upload'); echo "<h2>" .  __( 'GW Fonts Options', TEMPLATE_DOMAIN ) . "</h2>"; ?>
<?php
if ( $_REQUEST['saved'] ) echo '<div class="updated fade"><p><strong>'.  __('GWF settings saved.', TEMPLATE_DOMAIN) . '</strong></p></div>';
if ( $_REQUEST['reset'] ) echo '<div class="updated fade"><p><strong>'.  __('GWF settings reset.', TEMPLATE_DOMAIN) . '</strong></p></div>';

if($get_font_transiet == FALSE):
echo '<div class="updated fade"><p><strong>'.  __('You need to update or save the google font list first.', TEMPLATE_DOMAIN) . '</strong></p></div>';
else:
?>

<form id="wp-theme-options" method="post" action="" enctype="multipart/form-data">

<table class="form-table">

<?php foreach ($gwf_options as $value) { ?>

<?php if ( $value['header-title'] != "" ) { ?>
<tr class="trtitle" valign="top"><th scope="row">
<h3><?php echo stripslashes($value['header-title']); ?></h3></th></tr>
<?php } ?>

<?php if ( $value['type'] == "select" ) { ?>

<tr class="<?php echo $value['hide_blk']; ?>" valign="top"><th scope="row"><?php echo $value['name']; ?></th>
<td>
<select name="<?php echo $value['id']; ?>" id="<?php echo $value['id']; ?>">
<?php foreach ( $value['options'] as $option ) { ?>
<option<?php if ( get_option( $value['id'] ) == $option) { echo ' selected="selected"'; } elseif ($option == $value['default']) { echo ' selected="selected"'; } ?>><?php echo $option; ?></option>
<?php } ?>
</select>
<div style="border:1px solid #ddd;margin:20px 0 0;width:400px;padding:20px;background:#f8f8f8;" class="testtextbox" id="testtext<?php echo $value['id']; ?>">The Quick Brown Fox Jumps Over The Lazy Dog. 1234567890</div>
<br />
<label class="description" for="<?php echo $value['id']; ?>"><?php echo $value['description']; ?></label>
</td>
</tr>

<?php } ?>

<?php } ?>
</table>

<div style="float: left; margin: 20px 40px 0 0;" class="submit">
<input name="save" type="submit" class="button-primary sbutton" value="<?php echo esc_attr(__('Save Setting',TEMPLATE_DOMAIN)); ?>" /><input type="hidden" name="action" value="save" />
</div>
</form>

<form method="post">
<div style="float: left; margin: 20px 40px 0 0;" class="submit">
<?php
$alert_message = __("Are you sure you want to delete the fonts options?.", TEMPLATE_DOMAIN ); ?>
<input name="reset" type="submit" class="button-secondary" onclick="return confirm('<?php echo $alert_message; ?>')" value="<?php echo esc_attr(__('Reset Setting',TEMPLATE_DOMAIN)); ?>" />
<input type="hidden" name="action" value="reset" />
</div>
</form>

</div>

<?php endif; }

Step 4 – Preparing wp_gwf_fonts_update()

Another function are the Google web fonts update panel. Here you can add your own Web Fonts API and update the available font family list and sort them by alpha, trend or popularity.

function wp_gwf_fonts_update() {
global $get_font_transiet;
?>
<div id="custom-theme-option" class="wrap">
<?php screen_icon('upload'); echo "<h2>" .  __('Google Web Fonts Family', TEMPLATE_DOMAIN ) . "</h2>";
if ( $_REQUEST['saved'] ) {
echo '<div class="updated fade"><p><strong>'.  __('Google Web Fonts Family Successfully Updated.', TEMPLATE_DOMAIN) . '</strong></p></div>';
}
?>

<form id="wp-theme-options" method="post" action="" enctype="multipart/form-data">
<?php
//register the $_POST variable
$gwf_font_api = $_POST['google-font-dev-api'];
$gwf_font_sort = $_POST['google-font-sort'];

//if save button hit
if( $_POST['save']  ) {

//if no dev font api set
if( !isset($gwf_font_api) ):
echo '<div class="error"><p><strong>'.  __('Google Web Fonts API not set.', TEMPLATE_DOMAIN) . '</strong></p></div>';
endif;

update_option('google-font-sort',$gwf_font_sort);
update_option('google-font-api',$gwf_font_api);

$get_gwf_font_api = get_option('google-font-sort');
$get_gwf_font_api = get_option('google-font-api');
$fontlist = wp_get_google_webfonts_list($gwf_font_api, $gwf_font_sort);

// delete and renew transient with expiration for font list
delete_transient( 'wp_gwf_list_save' );
set_transient( 'wp_gwf_list_save', $fontlist );

// save and store the transient and redirect
echo "<SCRIPT LANGUAGE='JavaScript'>
window.location='". admin_url('/'). "admin.php?page=google-fonts-update&update=true" . "';
</script>";

}

if( $get_font_transiet == FALSE ):
echo '<div class="updated fade"><p><strong>'.  __('You need to update or save the google font list first.', TEMPLATE_DOMAIN) . '</strong></p></div>'; ?>

<?php else: ?>

<table class="form-table">
<h3><?php echo count($get_font_transiet); ?> <?php _e('available Google Web Fonts', TEMPLATE_DOMAIN); ?>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<small><a href="#google-font-dev-api">Update the font family below</a></small></h3>
<tr valign="top">
<td>
<?php
foreach($get_font_transiet as $font): ?>
<?php echo '<p style="width:250px;height:30px;float:left;margin:0;">'. ucfirst($font) . '</p>'; ?>
<?php endforeach; ?>
</td>
</tr>
</table>

<?php endif; ?>

<div style="float: left; margin: 40px 20px 0 0;" class="submit">

<label><strong><?php _e('Enter Your Web Fonts Developer API', TEMPLATE_DOMAIN); ?></strong></label>&nbsp;&nbsp;
<input style="width:300px;" id="google-font-dev-api" name="google-font-dev-api" type="text" value="<?php echo get_option('google-font-api'); ?>" />
&nbsp;&nbsp;&nbsp;<label><strong><?php _e('Sort by', TEMPLATE_DOMAIN); ?></strong></label>&nbsp;&nbsp;<select id="google-font-sort" name="google-font-sort">
<option<?php if ( get_option('google-font-sort') == 'alpha') { echo ' selected="selected"'; } ?>>alpha</option>
<option<?php if ( get_option('google-font-sort') == 'date') { echo ' selected="selected"'; } ?>>date</option>
<option<?php if ( get_option('google-font-sort') == 'popularity') { echo ' selected="selected"'; } ?>>popularity</option>
<option<?php if ( get_option('google-font-sort') == 'style') { echo ' selected="selected"'; } ?>>style</option>
<option<?php if ( get_option('google-font-sort') == 'trending') { echo ' selected="selected"'; } ?>>trending</option>
</select>&nbsp;&nbsp;&nbsp;
</div>

<div style="float: left; margin: 40px 10px 0 0;" class="submit">
<input name="save" type="submit" class="button-primary sbutton" value="<?php echo esc_attr(__('Update Fonts List',TEMPLATE_DOMAIN)); ?>" /><input type="hidden" name="action" value="save" />
</div>

<div style="color:#666;width:100%; float: left; margin: 0;" >
<small>Web Fonts Developer API Example: AIzaSyBmPRa5TGlBRbUUV-pVPU3GxXRkD4lBtUU<br /><br />
alpha: Sort the list alphabetically <br />
    date: Sort the list by date added (most recent font added or updated first) <br />
    popularity: Sort the list by popularity (most popular family first)
    style: Sort the list by number of styles available (family with most styles first) <br />
    trending: Sort the list by families seeing growth in usage (family seeing the most growth first)
</small>
</div>

</form>

</div>

<?php } ?>

Are we finished? not yet, we need to add 2 more functions for the Font Preview and Google web fonts in site and admin dashboard to work, its quite easy, just add these:

Step 5 – Add hook action for wp_head() and admin_head()

///////////////////////////////////////////////////////////////////
// get google web font for homepage
///////////////////////////////////////////////////////////////////
if( !function_exists( 'wp_gwf_header_init' ) ):
function wp_gwf_header_init(){

$http = (!empty($_SERVER['HTTPS'])) ? "https" : "http";
$un_bodytype = get_option('_body_font');
$un_headtype = get_option('_headline_font');
$bodytype = str_replace(' ' , '+', get_option('_body_font'));
$headtype = str_replace(' ' , '+', get_option('_headline_font'));
$font_var = '300,400,600,700,900,300italic,400italic,600italic,700italic,900italic';

if ( $bodytype != "" ){
echo "<link href='" . $http . "://fonts.googleapis.com/css?family=" . $bodytype . ":" . $font_var . "' rel='stylesheet' type='text/css'>";
}

if ($headtype != ""){
echo "<link href='" . $http . "://fonts.googleapis.com/css?family=" . $headtype . ":" . $font_var . "' rel='stylesheet' type='text/css'>";
}

?>

<?php echo "<style type='text/css' media='all'>"; ?>
body { font-family: <?php echo get_option('_body_font'); ?> !important; }
h1,h2,h3,h4,h5,h6 { font-family: <?php echo get_option('_headline_font'); ?> !important; }
<?php echo "</style>"; ?>

<?php }

endif;
add_action('wp_head','wp_gwf_header_init');

and for admin panel font preview

///////////////////////////////////////////////////////////////////
// get google web font for admin
///////////////////////////////////////////////////////////////////
if( !function_exists( 'wp_gwf_admin_header_init' ) ):
function wp_gwf_admin_header_init() {

if ( $_GET['page'] == 'google-fonts-settings' ) {  ?>

<script type="text/javascript">
jQuery(document).ready(function(){
jQuery("select#<?php echo '_body_font'; ?>, select#<?php echo '_headline_font'; ?>").change(function(){
var val = jQuery("select#<?php echo '_body_font'; ?>").val();
var val2 = jQuery("select#<?php echo '_headline_font'; ?>").val();
//var valx = val.replace(/ /g, "+");
jQuery("#cFontStyleWColor11").text('#testtext<?php echo "_body_font"; ?> { font-size: 16px; font-family: "'+ val +'" !important; }');
jQuery("#cFontStyleWColor12").text('#testtext<?php echo "_headline_font"; ?> { font-size: 16px; font-family: "'+ val2 +'" !important; }');

WebFontConfig = {
google: { families: [ ''+ val +'', ''+ val2 +'' ] }
};
(function() {
        var wf = document.createElement('script');
        wf.src = ('https:' == document.location.protocol ? 'https' : 'http') +
            '://ajax.googleapis.com/ajax/libs/webfont/1/webfont.js';
        wf.type = 'text/javascript';
        wf.async = 'true';
        var s = document.getElementsByTagName('script')[0];
        s.parentNode.insertBefore(wf, s);
      })();
});
});
</script>

<style id="cFontStyleWColor11" type="text/css"></style>
<style id="cFontStyleWColor12" type="text/css"></style>

<?php
$http = (!empty($_SERVER['HTTPS'])) ? "https" : "http";
$un_bodytype = get_option('_body_font');
$un_headtype = get_option('_headline_font');
$bodytype = str_replace(' ' , '+', get_option('_body_font'));
$headtype = str_replace(' ' , '+', get_option('_headline_font'));
$font_var = '300,400,600,700,900,300italic,400italic,600italic,700italic,900italic';

if ( $bodytype != "" ){
echo "<link href='" . $http . "://fonts.googleapis.com/css?family=" . $bodytype . ":" . $font_var . "' rel='stylesheet' type='text/css'>";
}

if ($headtype != ""){
echo "<link href='" . $http . "://fonts.googleapis.com/css?family=" . $headtype . ":" . $font_var . "' rel='stylesheet' type='text/css'>";
}
?>

<?php echo "<style type='text/css' media='all'>"; ?>
<?php if( get_option('_body_font') ): ?>
#testtext<?php echo "_body_font"; ?> {
font-size: 16px; font-family: <?php echo get_option('_body_font'); ?>;
}
<?php endif; ?>

<?php if( get_option('_body_font') ): ?>
#testtext<?php echo "_headline_font"; ?> {
font-size: 16px; font-family: <?php echo get_option('_headline_font'); ?>;
}
<?php endif; ?>
<?php echo "</style>"; ?>

<?php } }

endif;

add_action('admin_head','wp_gwf_admin_header_init');

Step 6 – You’re done, start testing

If everything is in place, you should be able to see a GWF Fonts Menu with two sub-menu GWF Fonts settings and GWF Fonts update.

To get started, you need to update the font list in GWF Fonts update sub-menu. If you have your own Web Font API then add in the textfield. if not use the default API included there.

You will see something like this if the font list successfully store in get_transient().

gwf-font-list

To finalize test, go to GWF Fonts setting and Choose which font you want for body and headline text and save the setting. Finally go to your homepage and see the Google Web Fonts now replaced all your body text and Headline Text.

Don’t like to get your hand dirty?

Felling dizzy and confuse looking at all the codes, just download the source code below and add to your current activated theme root. wp-content/themes/current-themes/–upload here–
and add this to your functions.php file
include( get_template_directory() . '/gwf-options.php');

Download GWF Tutorial Source Code
File format: zip    File size: 7.31KB
How to add Google Web Fonts with Font Preview in WordPress without Pluginshttp://cdn.dezzain.com/1/2013/05/google-web-fonts-with-preview.pnghttp://cdn.dezzain.com/1/2013/05/google-web-fonts-with-preview-300x300.png Richie KS WordPress Tutorialsadd menu page,add submenu page,Editor Picks,google web fonts
Easy step by step WordPress tutorial on How to add Google Web Fonts with Font Preview and Font Options in WordPress Themes without any WordPress Plugins

19 Comments Already

  1. It seems like the !important tags in the wp_head hook (body { font-family: !important; }) are causing Internet Explorer to recognize the inline style that is created by the hook even when the plugin is not being used. In turn, it is overriding the initial google fonts that are set in the theme and displaying fallback fonts like arial and helvetica. Can you think of any way around this?

    Public CommentUserIt seems like the !important tags in the wp_head hook (body { font-family: !important; }) are causing Internet Explorer to recognize the inline style that is created by the hook even when the plugin is not being used. In turn, it is overriding the initial google fonts that are set in the theme and displaying fallback fonts like arial and helvetica. Can you think of any way around this?
  2. Firstly thanks for this awesome code..
    The preview is working only for the 1st time.. when i change the font family again, the preview doesn’t work. Any clue?

    Thanks

    Public CommentUserFirstly thanks for this awesome code.. The preview is working only for the 1st time.. when i change the font family again, the preview doesn't work. Any clue? Thanks
    • some api changes from the google webfont that cause the ‘preview’ not work but it will work on saved google font. will try update this tutorial.

      Member of Dezzain.comAdministratorsome api changes from the google webfont that cause the 'preview' not work but it will work on saved google font. will try update this tutorial.
  3. I’ve been using Google fonts on my website http://www.moreonfew.com/ and I must say that it is really worth the effort. Not only is it faster but also provides a large number of fonts to choose from; all for free!

    Public CommentUserI've been using Google fonts on my website http://www.moreonfew.com/ and I must say that it is really worth the effort. Not only is it faster but also provides a large number of fonts to choose from; all for free!
  4. Very useful…Great thanks

    Public CommentUserVery useful...Great thanks
  5. Is it OK if I use the code in this tutorial for a theme that I will be selling? I will reference this page in the credits.

    Public CommentUserIs it OK if I use the code in this tutorial for a theme that I will be selling? I will reference this page in the credits.
    • sure go ahead.

      Member of Dezzain.comAdministratorsure go ahead.
  6. Thanks very much for such nice tutorial but I downloaded the source, and it doesnt work for me, it keeps telling me “You need to update or save the google font list first.”

    Public CommentUserThanks very much for such nice tutorial but I downloaded the source, and it doesnt work for me, it keeps telling me "You need to update or save the google font list first."
    • yes, you need to enter your google dev api or use the default one and save the options.

      Member of Dezzain.comAdministratoryes, you need to enter your google dev api or use the default one and save the options.
      • I did but I still have this problem :S…

        Public CommentUserI did but I still have this problem :S...
        • did you enter this AIzaSyBmPRa5TGlBRbUUV-pVPU3GxXRkD4lBtUU must be exact, no extra space etc

          Member of Dezzain.comAdministratordid you enter this <code>AIzaSyBmPRa5TGlBRbUUV-pVPU3GxXRkD4lBtUU</code> must be exact, no extra space etc
  7. What is your recommended policy for using the web font developer API key?

    Can one key be obtained per developer, and this key used on all websites the developer’s theme is used on?

    Or does the user need to sign up for a developer key themselves?

    Thanks.

    Public CommentUserWhat is your recommended policy for using the web font developer API key? Can one key be obtained per developer, and this key used on all websites the developer's theme is used on? Or does the user need to sign up for a developer key themselves? Thanks.
    • depends, its better to have one developer key for not more than 10-50 website since there’s limit to dev api request per hour i think.

      Member of Dezzain.comAdministratordepends, its better to have one developer key for not more than 10-50 website since there's limit to dev api request per hour i think.
  8. Wow, this is pretty. It’s always good to be able to preview the font first before using it.

    Public CommentUserWow, this is pretty. It's always good to be able to preview the font first before using it.
  9. Hi! I try this tutorial but there are many errors with debug mode active.

    Notice: Undefined index: action in
    Notice: Undefined index: saved in
    Notice: Undefined index: reset in
    Undefined index: google-font-sort in
    Undefined index: google-font-dev-api in

    Public CommentUserHi! I try this tutorial but there are many errors with debug mode active. Notice: Undefined index: action in Notice: Undefined index: saved in Notice: Undefined index: reset in Undefined index: google-font-sort in Undefined index: google-font-dev-api in
  10. Excellent ! This is nice way to get the font api in wordpress theme. My theme using pro panel wordpress option panel ,. is there any way to add this font api functionality inside my theme option panel.

    Public CommentUserExcellent ! This is nice way to get the font api in wordpress theme. My theme using pro panel wordpress option panel ,. is there any way to add this font api functionality inside my theme option panel.
  11. Thanks for sharing your thoughts on how to add google web fonts in wordpress.
    Regards

    Public CommentUserThanks for sharing your thoughts on how to add google web fonts in wordpress. Regards
  12. i’ve been searching for something like this for ages. especially the font preview in web fonts functionality. thanks for the share richie ks.

    Public CommentUseri've been searching for something like this for ages. especially the font preview in web fonts functionality. thanks for the share richie ks.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>