Created
September 30, 2020 16:59
-
-
Save ceaksan/10017faeb900e19d3fd30cd7905a40a7 to your computer and use it in GitHub Desktop.
WordPress Plugin: nexGEN Gallery Image clicks to GA/GTM
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
<?php | |
/** | |
* Plugin Name: WP NextGENGalery Image Clicks | |
*/ | |
add_action('wp_footer', 'nextGENGallery_enqueue_custom_js'); | |
function nextGENGallery_enqueue_custom_js() { | |
if(is_page()) { | |
global $post; | |
$post_data = get_post($post->post_parent); | |
$parent_slug = $post_data->post_name; | |
$current_slug = $post->post_name; | |
$parentPage = ucwords(str_replace('-', ' ', $parent_slug)); | |
$currentPage = ucwords(str_replace('-', ' ', $current_slug)); | |
if($parent_slug == 'tattoo-designs') { | |
echo " | |
<script> | |
const nGGallery = document.querySelectorAll('.ngg-gallery-thumbnail a img'); | |
const getParentPageName = '". $parentPage ."' | |
const getCurrentPageName = '". $currentPage ."' | |
Array | |
.from(nGGallery) | |
.forEach(el => el.addEventListener('click', () => { | |
const image = el.getAttribute('src'); | |
const imageSplit = image.split('/'); | |
const imageSlashCount = imageSplit.length; | |
console.log(imageSplit[imageSlashCount-1]); | |
console.log(getParentPageName); | |
// if you use GA snippet on your website | |
// gtag('event', 'click', { | |
// 'event_category': 'image Click: ' + getParentPageName, | |
// 'event_label': imageSplit[imageSlashCount-1], | |
// 'value': 1 | |
// }); | |
// if you use GTM snippet on your website | |
window.dataLayer = window.dataLayer || []; | |
window.dataLayer.push({ | |
'event': 'imageclick', | |
'eventParentPage': getParentPageName, | |
'eventCurrentPage': getCurrentPageName, | |
'eventImageSrc': imageSplit[imageSlashCount-1], | |
}); | |
}) | |
); | |
</script>"; | |
} | |
} | |
} | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment