Last active
June 16, 2022 20:33
-
-
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.
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 | |
| 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