Last active
October 30, 2015 16:17
-
-
Save smeric/9693de828f5ee52cd9cd to your computer and use it in GitHub Desktop.
WordPress AddToAny custom script to : push shared data to datalayer for GTM, re-shape title to remove special characters & use shortlink for Twitter
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 | |
/** | |
* AddToAny : custom script inserted into the document head | |
* | |
* Push shared data to datalayer for GTM | |
* Re-shape title to remove special characters | |
* Use shortlink for Twitter | |
* | |
* see https://www.addtoany.com/ext/google_analytics/ | |
* see https://www.addtoany.com/buttons/customize/wordpress/events | |
**/ | |
add_action( 'wp_head', 'add2any_custom_js', 999 ); | |
function add2any_custom_js(){ | |
global $post; | |
?> | |
<script> | |
// Init AddToAny objects | |
var a2a_config=a2a_config||{}; | |
a2a_config.callbacks=a2a_config.callbacks||[]; | |
// GA events tracking | |
a2a_config.callbacks.push({ | |
share: function(data) { | |
// Track shares in Google Analytics with Google Tag Manager | |
dataLayer.push({ | |
"event" : "<?php _e( 'Share with AddToAny', 'text-domain' ) ?>", | |
"socialAction" : "<?php _e( 'Social share', 'text-domain' ) ?>", | |
"socialNetwork": data.service, | |
"socialTarget" : data.url | |
}); | |
// Shared data | |
<?php if ( is_singular() ) { ?> | |
// Corectly encoded title | |
data.title = <?php | |
$title = html_entity_decode( strip_tags( get_the_title( $post->ID ) ), ENT_QUOTES ); | |
$sanitized_title = function_exists( 'wp_json_encode' ) ? wp_json_encode ( $title ) : json_encode( $title ); | |
echo $sanitized_title; | |
?>; | |
<?php } ?> | |
// Short url for Twitter share | |
if ( 'Twitter' === data.service ) { | |
data.url = "<?php echo wp_get_shortlink() ?>" | |
} | |
// Log data to console for debug purpose | |
console.log( 'AddToAny shared object : ' + data ); | |
return data; | |
} | |
}); | |
</script> | |
<?php | |
} | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment