Add Google Analytics to WordPress Website

Adding google analytics code to your wordpress website is easy. This article will describe how to accomplish that without any plugin, manually in a simple manner.

Step 1 : Creating the widget area.
We shall first create a widget area to which you can add the google analytics code using a text widget from the widgets section of your admin area.

add the following code to your themes function.php file at the top of the file.

function additional_widgets_init() {
register_sidebar( array(
		'name'          => 'Widget For Google Analytics',
		'id'            => 'widget-for-google-analytics',
		'before_widget' => '',
		'after_widget'  => '',
		'before_title'  => '',
		'after_title'   => '',
	) );
}
add_action( 'widgets_init', 'additional_widgets_init' );

This will create a widget Widget For Google Analytics in your widgets area in admin.

Step 2 : Adding the Widget to the theme
The widget now has to be added to your theme.As the code of footer.php is called everytime any page is visited,and we require the google analytics code script also to be called everytime, we shall add the widget to the theme’s footer.php file

Open the footer.php file of your theme.

Locate the function wp_footer(); Add the following code after this function OR just before the closing tag

<?php /* widget for google analytics code */ 
	if ( is_active_sidebar( 'widget-for-google-analytics' ) ) : ?>
	
		<?php dynamic_sidebar( 'widget-for-google-analytics' ); ?> 
	
					
<?php endif; /* end widget for google analytics code */ ?>

This will add the widget to the theme.

Step 3 : Adding Google Analytics Code

Go to widgets area in Admin.

Drag a text widget to to the Widget Area “Widget For Google Analytics”, which will now be visible.Add your google analytics code to this text widget.

Save the widget.



That is all.

If you liked this article please do leave a reply and share it with friends.

Thanks.

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.