Skip to content

Instantly share code, notes, and snippets.

@chavesm
Last active April 18, 2021 09:23
Show Gist options
  • Save chavesm/ac8f855c427c0ee80721c0839257d30e to your computer and use it in GitHub Desktop.
Save chavesm/ac8f855c427c0ee80721c0839257d30e to your computer and use it in GitHub Desktop.
Send a social media icon click event to GA using MonsterInsights gtag.js API.
<!-- Example HTML -->
<p>
<a
href="https://www.facebook.com"
onclick="sendSocialClick1209416('Facebook', 'https://streetphotography.blog');"
target="_blank"
rel="noopener">
Facebook
</a>
&nbsp;•&nbsp;
<a
href="https://twitter.com"
onclick="sendSocialClick1209416('Twitter', 'https://streetphotography.blog');"
target="_blank"
rel="noopener">
Twitter
</a>
&nbsp;•&nbsp;
<a
href="https://Instagram.com"
onclick="sendSocialClick1209416('Instagram', 'https://streetphotography.blog');"
target="_blank"
rel="noopener">
Instagram
</a>
</p>
/**
* Send a custom event using the newer gtag.js API
* instead of the older analytics.js API.
*/
function sendSocialClick1209416(soc, link) {
__gtagTracker("event", "socialshare", {
event_category: "socialshare",
event_action: soc,
event_label: link,
});
}
/**
* Usage:
*
* - Install the JS code using a insert headers/footers plugin, theme settings,
* or a proper PHP filter hook in your child theme's functions.php file.
*
* - Placement: Place this JS function in the before </head> or,
* before </body> is for slightly better page speed results.
*
* - Call sendSocialClick1209416('Facebook', 'https://www.mycool.site'); instead of
* calling the old ga(); analytics.js function.
*/
<?php // Ignore this line if adding below to functions.php.
/* Inline script printed out in the footer */
function add_script_wp_footer_1209416() {
?>
<script>
function sendSocialClick1209416(soc, link) {
__gtagTracker("event", "socialshare", {
event_category: "socialshare",
event_action: soc,
event_label: link,
});
</script>
<?php
}
add_action('wp_footer', 'add_script_wp_footer_1209416');
@chavesm
Copy link
Author

chavesm commented Apr 18, 2021

See live demo.

GA real-time report results.

ga-realtime-events-socialshare-1024w

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment