Client Side

All the fancy frizz

Create a Google AdSense WordPress widget in minutes

Written by: Peter Fisher on June 25, 2012
Share on FacebookShare on Google+Tweet about this on TwitterShare on LinkedIn

Google AdSenseYou may of noticed that this blog now has two Google AdSense adverts in the right hand side bar. One is at the top (above the search widget) and the other is at the bottom (below the archives widget). So how did I put them there?

This post will show you how to create a Google AdSense widget for Word Press in a matter of minutes.

Step one: Create the advert

  1. Sign up to Google AdSense
  2. Create an advert by clicking on “My Ads” and then click on” New add unit”

Createing a new Google AddSense advert

3. Now click “Get Code” and save the JavaScript to text file for later

Step two: Create the Word Press widget

Widgets live in wp-content/plugins/ but I am using the Suffusion theme and wanted to create a widget in the themes directory .  So I put the widget in /wp-content/themes/suffusion/widgets. It doesn’t make a difference as long as the widget can be registered.

Create a new php file in the relevant directory and call it something like google-ad-sense-widget.php

A widget is a php class which includes these four methods:

  • constructor – Sets up the widgets options
  • update – Called when the widget is updated
  • form – Called when displaying the form in the admin section.  Usually this just has a title
  • widget – The widget its self. This is where to put any code that you want to execute

So lets start with a blank GoogleAdSenseWidget class like below:

// wp-content/themes/suffsion/widgets/google-ad-sense-widget.php
// OR
// wp-content/plugins/google-ad-sense-widget.php

class GoogleAdSenseWidget extends WP_Widget
{

        function GoogleAdSenseWidget()
        {
                // The constructor
        }

        function update($new_instance, $old_instance)
        {
                // Update method called when the widget is updated
        }

        function widget($args, $instance)
        {
                // Widget method home to all the widgety goodness
        }
}

Now lets set up the widgets constructor

function GoogleAdSenseWidget()
{
        $widget_ops = array(
        'classname' => 'GoogleAdSenseWidget', 
        'description' => 'Displays a Google AdSense advert'
        );

        $this->WP_Widget(
            'GoogleAdSenseWidget', 
            'Google AdSense', 
            $widget_ops
            );
}

Now the form method

function form($instance)
{
    $instance = wp_parse_args( (array) $instance, array( 'title' => '' ) );
    $title = $instance['title'];
?>
    <p>
        <label for="<?php echo $this->get_field_id('title'); ?>">Title:
            <input class="widefat" 
		id="<?php echo $this->get_field_id('title'); ?>" 
		name="<?php echo $this->get_field_name('title'); ?>" 
		type="text" 
		value="<?php echo attribute_escape($title); ?>" 
	    />
        </label>
    </p>

<?php } ?>

Now add the guts to the  update method

function update($new_instance, $old_instance)
{
        $instance = $old_instance;
        $instance['title'] = $new_instance['title'];
        return $instance;
}

Add finally add the internals to the widget method.  You will need to add the JavaScript AdSense code  that you saved earlier to the section marked   PLACE YOUR GOOGLE ADSENSE CODE HERE   (remember to remove the html comment tags from the example).

<?php
function widget($args, $instance)
{
        extract($args, EXTR_SKIP);

        echo $before_widget;
        $title = empty($instance['title']) ? ' ' : apply_filters('widget_title', $instance['title']);

        if (!empty($title))
        echo $before_title . $title . $after_title;;
        ?>

        <!--  PLACE YOUR GOOGLE ADDSENSE CODE HERE  -->
<?php

echo $after_widget;
}
?>

Now you should end up with a widget like this:

class GoogleAdSenseWidget extends WP_Widget
{
        function GoogleAdSenseWidget()
        {
                $widget_ops = array(
                'classname' => 'GoogleAdSenseWidget', 
                'description' => 'Displays a Google AdSense advert'
                );

                $this->WP_Widget(
                    'GoogleAdSenseWidget', 
                    'Google AdSense', 
                    $widget_ops
                    );
        }
 
        function form($instance)
        {
                $instance = wp_parse_args( (array) $instance, array( 'title' => '' ) );
                $title = $instance['title'];
                ?>
                <p>
                <label for="<?php echo $this->get_field_id('title'); ?>">Title:
                    <input class="widefat" id="<?php echo $this->get_field_id('title'); ?>" name="<?php echo $this->get_field_name('title'); ?>" type="text" value="<?php echo attribute_escape($title); ?>" />
                </label>
                </p>
                <?php
        }
 
        function update($new_instance, $old_instance)
        {
                $instance = $old_instance;
                $instance['title'] = $new_instance['title'];
                return $instance;
        }
 
        function widget($args, $instance)
        {
                extract($args, EXTR_SKIP);

                echo $before_widget;
                $title = empty($instance['title']) ? ' ' : apply_filters('widget_title', $instance['title']);

                if (!empty($title))
                echo $before_title . $title . $after_title;;

                ?>
                <!-- 
                        PLACE YOUR GOOGLE ADSENSE CODE HERE     
                -->

                echo $after_widget;
        }

Step Three: Registering the Google AdSense widget

The last thing we need to do is register the widget. Now if your not using the Suffusion theme then you just add the following line at the bottom of the class (after the last closing brace).

add_action( 'widgets_init', create_function('', 'return register_widget("GoogleAdSenseWidget");') );

If you are using the Suffusion theme then you will need to modify the Suffusion widgets file and include the widget.  If you open wp-content/themes/suffusion/suffusion-widgets.php you will see a bunch of include file calls. All you need to do is add the following:

/**
 * Loads up all the widgets defined by Suffusion. This functionality will be released as a plugin in a future release.
 *
 * @package Suffusion
 * @subpackage Widgets
 */
// wp-content/themes/suffusion/widgets/suffusion_widgets.php

if (!class_exists('Suffusion_Widgets')) {
        class Suffusion_Widgets {
                // ...
                function load_widgets() {
                        //..
                        
                        include_once ($template_path . '/widgets/google-ad-sense-widget.php');
                        
                        //..

                        register_widget("GoogleAddSenseWidget");
                }
        }
}

Go to your Word press admin section and click through to widgets. Drag the Google AdSense widget to the side bar, give it a title and hit save.

Job done – Make a coffee

Share on FacebookShare on Google+Tweet about this on TwitterShare on LinkedIn

Peter Fisher is a web developer working in Gloucester UK. Founder of the digital agency Websomatic, author of this blog and the HowToCodeWell Youtube channel. Peter has over ten years of web development experience under his belt

Read all about Peter Fisher

Leave a Reply

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