Advertisement
Business

Making the Best of Google AdSense in WordPress

by

Blog monetization is not a "must", but it's a very important source of motivation. Whether you're blogging alone or along with some authors you gathered, earning even a few bucks a month can change your and/or your authors' approach to your blog.

Since Google AdSense is one of the easiest and most popular ways for blog monetization, we're going to see how to use it with a WordPress blog with multiple authors. (Although, this tutorial will also work for single bloggers.) We'll be covering how to set up profile fields for authors' AdSense ads and how to display those ads with a function, with a widget, with a shortcode and automatically inside posts.


Warming Up: Setting Profile Fields for Authors' Own Ads

Google accepts ads from multiple AdSense publishers in the same website as long as you don't display ads from multiple publishers on the same page. Thus, we're going to display our authors' ads on their posts' pages and display our own ads on other pages.

We could ask every author in our blog for their AdSense code blocks and insert them manually in our code, but asking them to provide the code themselves and inserting them dynamically would be a better idea. (Plus, there's no fun in doing stuff manually.) The code below provides the functionality for our authors to update their profiles to insert their own AdSense ads:

<?php
// show the textarea fields for authors' to enter their AdSense ad codes
// source: http://www.stemlegal.com/greenhouse/2012/adding-custom-fields-to-user-profiles-in-wordpress/
function wptuts_profile_adsense_show( $user ) {
	echo '<h3>Your Google AdSense Ads</h3>
	<table class="form-table">
		<tr>
			<th><label for="adsense_300x250">AdSense Ad Code (300x250)</label></th>
			<td><textarea name="adsense_300x250" id="adsense_300x250" rows="5" cols="30">' . get_user_meta( $user->ID, 'adsense_300x250', true) . '</textarea><br>
			<span class="adsense_300x250">Your Google AdSense JavaScript code for the 300x250 ad space.</span></td>
		</tr>
		<tr>
			<th><label for="adsense_468x60">AdSense Ad Code (468x60)</label></th>
			<td><textarea name="adsense_468x60" id="adsense_468x60" rows="5" cols="30">' . get_user_meta( $user->ID, 'adsense_468x60', true) . '</textarea><br>
			<span class="adsense_468x60">Your Google AdSense JavaScript code for the 468x60 ad space.</span></td>
		</tr>
	</table>';
}
add_action( 'show_user_profile', 'wptuts_profile_adsense_show' );
add_action( 'edit_user_profile', 'wptuts_profile_adsense_show' );

// save the changes above
function wptuts_profile_adsense_save( $user_id ) {
	if ( ! current_user_can( 'edit_user', $user_id ) )
		return false;
	update_user_meta( $user_id, 'adsense_300x250', $_POST['adsense_300x250'] );
	update_user_meta( $user_id, 'adsense_468x60',  $_POST['adsense_468x60']  );
}
add_action( 'personal_options_update', 'wptuts_profile_adsense_save' );
add_action( 'edit_user_profile_update', 'wptuts_profile_adsense_save' );
?>

You can duplicate the table rows to add more ad types, if you want. Don't forget to change the names and other parameters of the inputs, though.


Building Our Main Function

Now, we get to the part where we build our main function that will be used both on its own and by other functions. Take a look at the code below:

<?php
// our main function to return the ad codes
// remember: other functions below use this function, too!
function wptuts_return_adsense( $ad_type = '468x60' ) {
	// the default ad codes - don't forget to change them!
	$default_ad_codes = array(
		'300x250' => '<img src="http://dummyimage.com/300x250" />',
		'468x60'  => '<img src="http://dummyimage.com/480x60" />'
	);
	if ( is_single() ) {
		global $post;
		$user_id = $post->post_author;
		$ad_code = get_user_meta( $user_id, 'adsense_' . $ad_type, true );
	} else {
		$ad_code = $default_ad_codes[$ad_type];
	}
	if ( $ad_code != '' ) {
		// we'll return the ad code within a div which has a class for the ad type, just in case
		return '<div class="adsense_' . $ad_type . '">' . $ad_code . '</div>';
	} else {
		return false;
	}
}
?>

You see what it does?

  1. First off, we define some "default ad codes" to show other than post pages.
  2. Then we check if the page is a "single post page".
  3. If it is a single post page, we fetch the ad codes from the post author's profile and define it in the $ad_code variable. Here, notice that we're also using the $ad_type parameter of the function.
  4. If it's not a single post page, we're defining the $ad_code variable with the default ad codes.
  5. And if the $ad_code variable is not empty, we return the ad code with a div surrounding it. (Otherwise, we return false.)

Done! You can use this function wherever you want inside your theme now - both inside and outside The Loop.

I love it when it's so simple! :)

Remember: Google strictly prohibits you from displaying ads from multiple publishers on the same page. That's why the main function (thus, other functions) will not display the "default ad codes" if the author didn't provide their own codes in their profile. If we did that, we would most definitely get banned from Google AdSense.

Creating the Shortcode

If you want to give your authors the liberty of adding their own ads anywhere inside their posts, you can use a shortcode like below:

<?php
// shortcode for the above function
// usage: [display_adsense ad_type="468x60"]
function display_adsense_sc( $atts ) {
	extract( shortcode_atts( array(
		'ad_type' => '468x60'
	), $atts ) );
	return wptuts_return_adsense( $ad_type );
}
add_shortcode( 'display_adsense', 'display_adsense_sc' );
?>

It's even simpler than the main function: It takes the ad_type parameter and passes it through our main function and returns the function.

If you don't want any parameters and just return the main function, you don't even need the code above! Just add this line after our main function:

<?php
// usage: [display_adsense]
add_shortcode( 'display_adsense', 'wptuts_return_adsense' );
?>

Our main function's only parameter has a default value ('468x60', in our example), so the shortcode will display that kind of ad only.


Inserting the Ads Automatically After "n"th Paragraph

You may not want to give the liberty to your authors to display ads in some cases. If you decide to insert their ads automatically, say, after the first paragraph of every post; the function below is exactly what you're looking for:

<?php
// the function to insert the ads automatically after the "n"th paragraph in a post
// the following code is borrowed from Internoetics, then edited:
// http://www.internoetics.com/2010/02/08/adsense-code-within-content/
function wptuts_auto_insert_adsense( $post_content ) {
	if ( !is_single() ) return $post_content;
	$afterParagraph = 1; // display after the "n"th paragraph
	$adsense = wptuts_return_adsense( '468x60' );
	preg_match_all( '/<\/p>/', $post_content, $matches, PREG_OFFSET_CAPTURE );
	$insert_at = $matches[0][$afterParagraph - 1][1];
	return substr( $post_content, 0, $insert_at) . $adsense . substr( $post_content, $insert_at, strlen( $post_content ) );
}
add_filter( 'the_content', 'wptuts_auto_insert_adsense' );
?>

If you're going to download the plugin that we're building now (with the Download button at the beginning of the post), don't forget that the line with the add_filter() function will be commented out. Uncomment it to enable this functionality.


Building the AdSense Widget

Building widgets can seem tricky, but it's actually really easy to make them. In our case, we're just going to echo our main function and allow the admin(s) of your blog to set the default parameter for it:

<?php
// the widget to display the ads on the sidebar
class Wptuts_AdSense_Widget extends WP_Widget {
	public function __construct() {
		parent::__construct(
			'wptuts_adsense_widget', // base ID of the widget
			'Wptuts+ AdSense Widget', // the name of the widget
			array( 'description' => 'Wptuts+ AdSense Widget Settings' ) // the description for the widget
		);
	}

	public function form( $instance ) {
		if ( isset( $instance[ 'ad_type' ] ) ) {
			$ad_type = $instance[ 'ad_type' ];
		} else {
			$ad_type = '300x250';
		}
		?>
		<p>
		<label for="<?php echo $this->get_field_id( 'ad_type' ); ?>">Ad Type</label> 
		<input class="widefat" id="<?php echo $this->get_field_id( 'ad_type' ); ?>" name="<?php echo $this->get_field_name( 'ad_type' ); ?>" type="text" value="<?php echo esc_attr( $ad_type ); ?>" />
		</p>
		<?php
	}

	public function update( $new_instance, $old_instance ) {
		$instance = array();
		$instance[ 'ad_type' ] = strip_tags( $new_instance[ 'ad_type' ] );
		return $instance;
	}

	public function widget( $args, $instance ) {
		echo wptuts_return_adsense( $instance[ 'ad_type' ] );
	}

}

function myplugin_register_widgets() {
	register_widget( 'Wptuts_AdSense_Widget' );
}

add_action( 'widgets_init', 'myplugin_register_widgets' );
?>

The widget also has a very simple function: If it's a single post page, display the author's ad and if it's not, display the default ad.


Conclusion

If you're running a blog with more than one author without a capital to pay for their work, these tricks could motivate them to write more often. They would even share and promote their own posts more eagerly - after all, they will have their own ads displayed on the pages. It's both clever and good!

Do you have any ideas about monetization of multi author blogs? Share your comments below!

Related Posts
  • Code
    Theme Development
    Creating a WordPress Theme from Static HTML: Creating an Archive TemplateCreating wordpress theme from html 400
    If you've been working your way through this series, you now have a functioning theme with two page templates. The steps I've demonstrated to this point are: preparing your markup for WordPress converting your HTML to PHP and splitting your file into template files editing the stylesheet and uploading your theme to WordPress adding a loop to your index file adding meta tags, the wp_head hook and the site title and description to your header file adding a navigation menu adding widget areas to the header and sidebar adding widget areas, a colophon and the wp_footer hook to the footer file creating template files for static pages. Read More…
  • Code
    Theme Development
    Creating a WordPress Theme From Static HTML: The Footer FileCreating wordpress theme from html 400
    In this series, you've been learning how to create a WordPress theme form static HTML. Up to this point, you have: prepared your markup for WordPress converted your HTML to PHP and split your file into template files edited the stylesheet and uploaded your theme to WordPress added a loop to your index file added meta tags, the wp_head hook and the site title and description to your header file added a navigation menu added widget areas to the header and sidebar. Read More…
  • Code
    Theme Development
    Creating a WordPress Theme from Static HTML - Adding WidgetsCreating wordpress theme from html 400
    In this series, you've learned how to convert a static HTML file to a WordPress theme and edit the header file. So far you've: prepared your markup for WordPress converted your HTML to PHP and split your file into template files edited the stylesheet and uploaded your theme to WordPress added a loop to your index file added meta tags, the wp_head hook and the site title and description to your header file added a navigation menu. Read More…
  • Code
    Theme Development
    Creating a WordPress Theme from Static HTML: Adding NavigationCreating wordpress theme from html 400
    If you've been working through this series, you now have a working theme with template files which you've uploaded to WordPress. In this tutorial, you'll continue to work on the header.php file that you created in Part 2. You'll learn how to add a navigation menu which can be edited via the WordPress Menus admin screen. To do this you'll also need to create a new file for your theme: the functions file.Read More…
  • Code
    Theme Development
    Creating a WordPress Theme From Static HTML: Adding a LoopCreating wordpress theme from html 400
    In the first three parts of this series, you learned how to prepare static HTML for WordPress and to create a theme by splitting your HTML file into a set of template files and editing the stylesheet. You then uploaded your theme to WordPress and activated it. The theme still isn't displaying any content you add via the WordPress admin however; to do that you need to add a loop to your template files.Read More…
  • Code
    Plugins
    Creating Client Testimonials With Custom Post TypesCreating client testimonials with custom post types
    If you're running any type of business online, it's a good idea to get your clients' opinions on what they thought about the services you provided. First of all, this can benefit you by giving you feedback on how you can improve aspects of your business, but most of all, it can give you great testimonials, which can help to persuade potential clients to use your services.Read More…