Skip to content

Instantly share code, notes, and snippets.

@kaelri
Last active June 16, 2022 20:33
Show Gist options
  • Select an option

  • Save kaelri/b2996ff5bd1b062f689872ec3552aa69 to your computer and use it in GitHub Desktop.

Select an option

Save kaelri/b2996ff5bd1b062f689872ec3552aa69 to your computer and use it in GitHub Desktop.
On WordPress singular attachment pages, send a custom Data Layer event to Google Tag Manager and then redirect to the raw file.
<?php
add_action( 'wp_footer', function() {
if ( !is_attachment() ) return;
$file_url = wp_get_attachment_url( get_the_ID() );
?><script>
document.addEventListener('DOMContentLoaded', function(){
var dataLayer = window.dataLayer;
var fileURL = '<?=esc_attr($file_url)?>';
if ( typeof dataLayer != 'object' ) {
window.location = fileURL;
return;
}
dataLayer.push({
event: 'wp_media_download',
url: fileURL,
eventCallback: function( id ) {
window.location = fileURL;
}
});
});
</script><?php
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment