Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save joselazovargas/3d14cc237375ba1eddb12a967a2b77a7 to your computer and use it in GitHub Desktop.
Save joselazovargas/3d14cc237375ba1eddb12a967a2b77a7 to your computer and use it in GitHub Desktop.
Modified Wordpress datalayer variables for pulling: author names, post types, categories, page name, and dates into custom variables for the classic version of Google Analytics. Feel free to leave a comment or hit me up http://BryanBarrera.com
// Add this script after you make your dataLayer = []; call
// AND after your GTM code snippet
// This needs to go inside the header.php in order for it work globally across your site
<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()){
// For: 404 page/ 404 errors
// 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_single()) {
// For: single posts
// Query the WP API to retrieve post type, author, category, and post name
$gtm_cat = get_the_category();
// Now we populate the Javascript data layer with our PHP variables
?>
"GTM_WP_pagename": "<?php print wp_title(); ?>",
"GTM_WP_authorname": "<?php print get_the_author(); ?>",
"GTM_WP_post_type": "<?php print get_post_type(); ?>",
"GTM_WP_Category": "<?php print $gtm_cat[0]->cat_name; ?>",
<?php } ?>
<?php if(is_page()|| is_category()) {
// We only want the page name and author name for pages and categories
// For: pages and categories
// Query the WP API to retrieve page name and author name
?>
"GTM_WP_pagename": "<?php print wp_title(); ?>",
"GTM_WP_authorname": "<?php print get_the_author(); ?>",
<?php }
// Date is appended to each if statement above
// Done with WordPress page type/conditions, you can add more default dataLayer variables below ?>
"GTM_WP_date": "<?php print get_the_date(); ?>",
<?php if (is_search()) {
// if it's a search
?>
"GTM_WP_search_query": "<?php print get_search_query(); ?>"
<?php } ?>
});
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment