CSM WordPress Theme v0.3

Posted in: Code, Web Design, Work on December 12th, 2014

Today my focus was on easy analytics code insertion into my WordPress theme… I had already setup MixPanel to track WordPress pages by page type, but I wanted to easily add analytics tracking code without digging into theme files. I use MixPanel, Heap Analytics and Google Tag Manager, and they required insertion in different parts of the page. Therefore, I created 3 new text areas in the options page which support html and js code, and hook directly into one of three action hooks:

  • wp_head: Inserts code just before the closing head tag (MixPanel and Heap go here).
  • wp_footer: Inserts code just after the opening footer tag.
  • csm_after_body: Custom action hook which inserts code just after the opening body tag (Google Tag Manager goes here).

View v0.3 on Github | Download Zip File of v0.3

Screenshot of the new options textareas
Screenshot of the new options textareas

Both wp_head and wp_footer are standard WordPress hooks; however, I added a new custom hook – csm_after_body – which provides an additional spot to hook to.

This is done by simply using the do_action function somewhere within a page template, and then hooking a function to it via functions.php, or in my case, the theme options page.

1
2
// this is added to the theme template file
do_action('csm_after_body'); 
// this is added to the theme template file
do_action('csm_after_body'); 
1
2
3
4
5
6
7
8
// This is the function used in the options page, but could just as well be used in functions.php
function csm_after_body_hook_html () {
  $options = get_option('csm_theme_settings');
  if($options['csm_theme_text_area_after_body_hook'] != "") {
    echo $options['csm_theme_text_area_after_body_hook'];
  }
}
add_action('csm_after_body','csm_after_body_hook_html');
// This is the function used in the options page, but could just as well be used in functions.php
function csm_after_body_hook_html () {
	$options = get_option('csm_theme_settings');
	if($options['csm_theme_text_area_after_body_hook'] != "") {
		echo $options['csm_theme_text_area_after_body_hook'];
	}
}
add_action('csm_after_body','csm_after_body_hook_html');
Share This:
Tagged:  

Leave a Reply