If you are not familiar with google web fonts this link is a good starting point.
Google fonts library has more than 500 fonts and still growing.



Using google web fonts will greatly increase visual appeal of your website.

You can check this magento theme settings panel on the left, to see how it will look with different google fonts.


Step First

First of all, we need to get list of available fonts. Here is sample script to get list of fonts separated by comma.

<html>
<body>
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
    var request = $.ajax({
        url: "https://www.googleapis.com/webfonts/v1/webfonts?key=YOUR-API-KEY",
        dataType: "jsonp",
        success: function(json){
            for (var i in json.items) {
                document.write(json.items[i].family+',');
            }
        }
    });    
});
</script>
</body>
</html>

Note, that you need to change YOUR-API-KEY in https://www.googleapis.com/webfonts/v1/webfonts?key=YOUR-API-KEY to your personal key.

More info can be found here.


Adding list of fonts to magento configuration

Now we will create simple magento extension to add configuration parameter in magento admin.
You can download extension source at the bottom of this page, by clicking “download” button.

Magento extension name is Namespace_Packagename – in our example, we called our extension Olegnax_Gfont

1. Add a module to your Magento system

So, to add a module to your Magento system, you need to create following directory structure:

app/code/local/Olegnax/Gfont/Block
app/code/local/Olegnax/Gfont/etc
app/code/local/Olegnax/Gfont/Helper
app/code/local/Olegnax/Gfont/Model



2. Let Magento know about your module.

Create app/etc/modules/Olegnax_Gfont.xml

<?xml version="1.0"?>
<config>
    <modules>
        <Olegnax_Gfont>
            <active>true</active>
            <codePool>local</codePool>
        </Olegnax_Gfont>
    </modules>
</config>



3. Create extension config

app/code/local/Olegnax/Gfont/etc/config.xml.
Config is a heart of extension. Here we set extension version, add it access control system,
define classes names for blocks, modules and helpers. Finally, we set default values for our parameters.

<?xml version="1.0"?>
<config>

    <modules>
        <Olegnax_Gfont>
            <version>0.1.0</version>
        </Olegnax_Gfont>
    </modules>

	<adminhtml>
		<acl>
			<resources>
				<admin>
					<children>
						<system>
			                <children>
			                    <config>
			                        <children>
			                            <gfont>
			                                <title>Olegnax Google Fonts</title>
			                            </gfont>
			                        </children>
			                    </config>
			                </children>
			            </system>
					</children>
				</admin>
			</resources>
		</acl>
    </adminhtml>

	<global>
        <blocks>
            <gfont>
                <class>Olegnax_Gfont_Block</class>
            </gfont>
        </blocks>
        <helpers>
            <gfont>
                <class>Olegnax_Gfont_Helper</class>
            </gfont>
        </helpers>
		<models>
            <gfont>
                <class>Olegnax_Gfont_Model</class>
            </gfont>
        </models>
    </global>

	<default>
		<gfont>
			<gfont_config>
				<font>Abel</font>
			</gfont_config>
		</gfont>
	</default>

</config>

You can find more detailed description of config sections here



4. Adding parameter to magento config system

You need to create app/code/local/Olegnax/Gfont/etc/system.xml.
This xml file is pretty self-explanatory. It will add a tab named “Olegnax” to magento config. Inside we create a section called gfont, add a group of parameters to it and finally add ‘font’ parameter. It will keep font name we want to use.

<?xml version="1.0"?>
<config>
	<tabs>
		<olegnax translate="label" module="gfont">
			<label>Olegnax</label>
			<sort_order>205</sort_order>
		</olegnax>
	</tabs>
	<sections>
		<gfont translate="label" module="gfont">
			<label>Olegnax Google Fonts</label>
			<tab>olegnax</tab>
			<sort_order>10</sort_order>
			<show_in_default>1</show_in_default>
			<show_in_website>1</show_in_website>
			<show_in_store>1</show_in_store>
			<groups>
				<gfont_config translate="label">
					<label>Olegnax Google Fonts Config</label>
					<frontend_type>text</frontend_type>
					<sort_order>10</sort_order>
					<show_in_default>1</show_in_default>
					<show_in_website>1</show_in_website>
					<show_in_store>1</show_in_store>
					<fields>
						<font translate="label comment">
							<label>Font: </label>
							<frontend_type>select</frontend_type>
							<frontend_model>gfont/adminhtml_system_config_form_field_font</frontend_model>
							<source_model>gfont/config_font</source_model>
							<sort_order>40</sort_order>
							<show_in_default>1</show_in_default>
							<show_in_website>1</show_in_website>
							<show_in_store>1</show_in_store>
						</font>
					</fields>
				</gfont_config>
			</groups>
		</gfont>
	</sections>
</config>

Please note, that we use custom frontend_model and source_model.
Frontend model responsible for config parameter html.
Source_model – for parameter options.

<frontend_model>gfont/adminhtml_system_config_form_field_font</frontend_model>
<source_model>gfont/config_font</source_model>



5. Lets create source_model.

app/code/local/Olegnax/Gfont/Model/Config/Font.php
Your source model should contain public method ‘toOptionArray’. It should return an array in folowing format:
[
    [ value = '', label = '' ]
    [ value = '', label = '' ]
    …
    [ value = '', label = '' ]
]

‘$gfonts’ variable keep fonts list separated by comma. Replace it with full list using script we wrote above.

<?php

class Olegnax_Gfont_Model_Config_Font
{
	/**
	 * google fonts list
	 *
	 * @var string
	 */
	private $gfonts = "Abel,Abril Fatface,Aclonica,Acme,Actor,Adamina,Aguafina Script,Aladin,Aldrich,Alegreya,Alegreya SC,Alex Brush,Alfa Slab One,Alice,Alike,Alike Angular,Allan,Allerta,Allerta Stencil,Allura,Almendra,Almendra SC,Amaranth,Amatic SC,Amethysta,Andada,Andika,Annie Use Your Telescope,Anonymous Pro,Antic,Anton,Arapey,Arbutus,Architects Daughter,Arimo,Arizonia,Armata,Artifika,Arvo,Asap,Asset,Astloch,Asul,Atomic Age,Aubrey,Bad Script,Balthazar,Bangers,Basic,Baumans,Belgrano,Bentham,Bevan";

    public function toOptionArray()
    {
	    $fonts = explode(',', $this->gfonts);
	    $options = array();
	    foreach ($fonts as $f ){
		    $options[] = array(
			    'value' => $f,
			    'label' => $f,
		    );
	    }

        return $options;
    }

}



6. Move to frontend_model.

app/code/local/Olegnax/Gfont/Block/Adminhtml/System/Config/Form/Field/Font.php
We want to extend default selectbox and add preview area for selected font. We will create small prototype class for this purposes.
Add div with id=”olegnax_gfont_preview” after selectbox.

Then add prototype class with following methods:

initialize (init font element and preview element)
bindFontChange (bind our function on font selectbox when following events fired)
   – keyup
   – keydown
   – change
refreshPreview (get selectbox value, check if we already load it, if not – load it, and update font family property for preview container)
updateFontFamily (update font family for preview container)

<?php

class Olegnax_Gfont_Block_Adminhtml_System_Config_Form_Field_Font extends Mage_Adminhtml_Block_System_Config_Form_Field
{
    /**
     * Override field method to add js
     *
     * @param Varien_Data_Form_Element_Abstract $element
     * @return String
     */
    protected function _getElementHtml(Varien_Data_Form_Element_Abstract $element)
    {
        // Get the default HTML for this option
        $html = parent::_getElementHtml($element);

        $html .= '<br/><div id="olegnax_gfont_preview" style="font-size:20px; margin-top:5px;">The quick brown fox jumps over the lazy dog</div>
		<script>
        var googleFontPreviewModel = Class.create();

        googleFontPreviewModel.prototype = {
            initialize : function()
            {
                this.fontElement = $("'.$element->getHtmlId().'");
                this.previewElement = $("olegnax_gfont_preview");
                this.loadedFonts = "";

                this.refreshPreview();
                this.bindFontChange();
            },
            bindFontChange : function()
            {
                Event.observe(this.fontElement, "change", this.refreshPreview.bind(this));
                Event.observe(this.fontElement, "keyup", this.refreshPreview.bind(this));
                Event.observe(this.fontElement, "keydown", this.refreshPreview.bind(this));
            },
        	refreshPreview : function()
            {
                if ( this.loadedFonts.indexOf( this.fontElement.value ) > -1 ) {
                    this.updateFontFamily();
                    return;
                }

        		var ss = document.createElement("link");
        		ss.type = "text/css";
        		ss.rel = "stylesheet";
        		ss.href = "http://fonts.googleapis.com/css?family=" + this.fontElement.value;
        		document.getElementsByTagName("head")[0].appendChild(ss);

                this.updateFontFamily();

                this.loadedFonts += this.fontElement.value + ",";
            },
            updateFontFamily : function()
            {
                $(this.previewElement).setStyle({ fontFamily: this.fontElement.value });
            }
        }

        googleFontPreview = new googleFontPreviewModel();
		</script>
        ';
        return $html;
    }
}



7. Create helper file

app/code/local/Olegnax/Gfont/Helper/Data.php
A lot of the Magento System code assumes that module has default Helper class. So you need to have it.

<?php
class Olegnax_Gfont_Helper_Data extends Mage_Core_Helper_Abstract
{
}



Now extension is ready.

Go to System -> Cache management, select all items, select refresh action and submit it.
Now go to System -> Configuration. You should see ‘Olegnax’ section in left column. If you click on it you will probably get 404 page.
You need to log out and then log in to update magento access control lists. After that you will see fonts select and sample preview text.



How to use it in frontend?

Lets pretend that you are using template called your_theme inside default package.
Copy head.phtml from app/design/frontend/base/default/template/page/html/head.phtml
to
app/design/frontend/default/your_theme/template/page/html/head.phtml or use your file if you already have it in your template.

To get font value from config use ‘Mage::getStoreConfig’ method

$font = Mage::getStoreConfig('gfont/gfont_config/font');

After that we need to load font from google.

<link href='//fonts.googleapis.com/css?family=<?php echo str_replace(' ', '+', $font); ?>' rel='stylesheet' type='text/css'>

Now, you can use it for your elements in css files or create style block and update it right in head.phml. Like this:

<style>
.page-title h1, .page-title h2 { font-family: '<?php echo $font; ?>', sans-serif; }
</style>



The End.

We hope you found this article useful, and if so, then feel free to share it with other people :)


Download for free