Last active
July 27, 2020 21:31
-
-
Save dotherightthing/864d7eac8c58e7f6378a5ca9584ee731 to your computer and use it in GitHub Desktop.
Google Tag Manager snippet #wordpress #templates #library #seo
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
/** | |
* Add Google Tag Manager | |
* | |
* @see http://kb.dotherightthing.dan/seo/google-tag-manager-gtm/ | |
* @example | |
* add_action( 'wp_enqueue_scripts', 'wpdtrt_dbth_js_link_gtm' ) | |
*/ | |
function wpdtrt_dbth_js_link_gtm() { | |
/** | |
* Link assets to theme version to ensure user gets the latest version | |
* | |
* @see https://wordpress.org/ideas/topic/add-theme-version-number-to-stylesheet-url-not-wp-version | |
*/ | |
$theme_version = wp_get_theme()->Version; | |
$header = 'inline_scripts_hook'; | |
// Check for ACF function. | |
if ( function_exists( 'get_field' ) ) { | |
wp_localize_script( | |
$header, | |
'wpdtrt_gtm_container_id', | |
get_field( 'wpdtrt_acf_gtm_container_id', 'option' ) | |
); | |
// Google Tag Manager. | |
wp_add_inline_script( $header, "(function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({'gtm.start': | |
new Date().getTime(),event:'gtm.js'});var f=d.getElementsByTagName(s)[0], | |
j=d.createElement(s),dl=l!='dataLayer'?'&l='+l:'';j.async=true;j.src= | |
'https://www.googletagmanager.com/gtm.js?id='+i+dl;f.parentNode.insertBefore(j,f); | |
})(window,document,'script','dataLayer',wpdtrt_gtm_container_id);" | |
); | |
} | |
} |
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
<?php | |
/** | |
* Include this partial immediately after the opening <body> tag. | |
* The <head> portion is loaded in js.php | |
* | |
* @see http://kb.dotherightthing.dan/seo/google-tag-manager-gtm/ | |
*/ | |
// Check for ACF function. | |
if ( function_exists( 'the_field' ) ) : | |
?> | |
<!-- Google Tag Manager (noscript) --> | |
<noscript><iframe src="https://www.googletagmanager.com/ns.html?id=<?php the_field( 'wpdtrt_acf_gtm_container_id', 'option' ); ?>" | |
height="0" width="0" style="display:none;visibility:hidden"></iframe></noscript> | |
<!-- End Google Tag Manager (noscript) --> | |
<?php | |
endif; | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment