Created
March 11, 2014 13:35
-
-
Save chipoglesby/9485698 to your computer and use it in GitHub Desktop.
Modified Wordpress datalayer variables for pulling: author names, post types, number of comments, categories, tags and dates into custom variables for the classic version of Google Analytics. Original script provided by Julien Coquet at: http://goo.gl/t3bz0M
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<script type="text/javascript"> | |
// URL toolbox - helps grabbing elements in the URL | |
var _d = document; | |
var _dl = _d.location; | |
var _dlp = _dl.pathname; | |
var _dls = _dl.search; | |
var _dr = _d.referrer; | |
// Initialize your data layer and start pushing variables from custom WordPress PHP data layer | |
dataLayer.push({ | |
<?php if (is_404()){ | |
// 404 pages, handled with a /404/ prefix as well as the referrer ?> | |
"GTM_WP_404": "<?php print is_404(); ?>", | |
"GTM_WP_404_URL": "/404" + _dlp + "/"+ _dr, | |
<?php } ?> | |
<?php if(is_home()){ | |
// Home page is tagged manually here but can be done directly in GTM | |
?> | |
"GTM_WP_post_type": "Home", | |
"GTM_WP_Category": "Home", | |
<?php } ?> | |
<?php if (is_single()||is_page()){ | |
/* Content pages: either a post or a page | |
* Query the WP API to retrieve post/page type, author, number of comments, tag, or even custom variables | |
*/ | |
$gtm_cat = get_the_category(); | |
//Get author ID | |
// post/page tags being passed as one big string separated by spaces | |
$posttags = get_the_tags(); | |
if ($posttags) { | |
foreach($posttags as $tag) { | |
$gtm_tags .= $tag->name . ' , '; | |
} | |
} | |
// Now we populate the Javascript data layer with our PHP variables | |
?> | |
"GTM_WP_authorname": "<?php the_author(); ?>", | |
"GTM_WP_post_type": "<?php print get_post_type(); ?>", | |
"GTM_WP_Number_Comments": "<?php print get_comments_number(); ?>", | |
"GTM_WP_Category": "<?php print $gtm_cat[0]->cat_name; ?>", | |
"GTM_WP_Tags": "<?php print trim($gtm_tags); ?>", | |
<?php } | |
// Done with WordPress page type/conditions, you can add more default dataLayer variables below ?> | |
"GTM_WP_date": "<?php print the_date( $format, $before, $after, $echo ); ?>" | |
}); | |
// Don't forget to terminate your data layer correctly! | |
</script> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thought I would share a more up to date snippet here for other users.
https://gist.github.com/BryanBarrera/124c934fd375c7509e74