Created
November 6, 2019 11:39
-
-
Save yumyo/8b3585ee95ead3617f380f4a60a511c6 to your computer and use it in GitHub Desktop.
WordPress Google Tag Manager Data Layer
This file contains 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
<!-- K Google Tag Manager Data Layer --> | |
<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(); // post/page tags being passed as one big string separated by spaces | |
$posttags = get_the_tags(); | |
if ($posttags) { | |
$gtm_tags = ''; | |
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_Category': '<?php if ( !empty( $gtm_cat ) ) { print $gtm_cat[0]->cat_name; }?>', | |
'GTM_WP_Tags': '<?php if ( !empty( $posttags ) ) { print trim($gtm_tags); } ?>', | |
<?php } // Done with WordPress page type/conditions, you can add more default dataLayer variables below | |
?> | |
'GTM_WP_dummy': 'Buckle your seatbelt Dorothy, because Kansas is going bye bye.' | |
}); | |
// 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