Skip to content

Instantly share code, notes, and snippets.

@jeherve

jeherve/plugin.php

Last active Feb 7, 2017
Embed
What would you like to do?
[Jetpack] Add tracking parameters to a post URL, and then have that tracked URL shortened by goo.gl, and then use that short URL in sharing buttons
<?php
/**
* Overwrite the links used in Jetpack's Sharing module.
*
* @see https://wordpress.org/support/topic/how-to-use-utm-codes-with-jetpack-sharing
*
* @param string $url
* @param int $post_id
* @param int $sharing_id
* @filter sharing_permalink
* @return string
*/
function jeherve_custom_sharedaddy_link( $url, $post_id, $sharing_id ) {
// Let's see if we have a shortlink for this post
$tracked_url = get_post_meta( $post_id, '_tracked_googl_shortlink', true );
if ( $tracked_url ) {
return $tracked_url;
} else {
// Let's build our tracking parameters
$ga_params = array(
'utm_source' => $sharing_id,
'utm_medium' => 'XXX',
'utm_term' => 'XXX',
'utm_content' => 'XXX',
'utm_campaign' => 'XXX',
);
// Add them to our post permalink
$tracked_url = esc_url( add_query_arg( $ga_params, $url ) );
/**
* Create a short Goo.gl URL redirecting to the full URL with tracking parameters.
*
* @see https://goo.gl/
*
* This uses my own API key by default.
* if you want to use your own to have stats attached to your own Goo.gl account,
* get your own key here: https://developers.google.com/url-shortener/v1/getting_started?hl=en
*/
$googl_key = 'AIzaSyDjjB4PmEYFAIH7NF9Q6vww7unzFk_e32s';
// Let's query Google and get a Short URL
$googl_result = wp_remote_post(
add_query_arg(
'key',
$googl_key,
'https://www.googleapis.com/urlshortener/v1/url'
),
array(
'body' => json_encode( array( 'longUrl' => esc_url_raw( $tracked_url ) ) ),
'headers' => array( 'Content-Type' => 'application/json' ),
)
);
// Return the default URL if the request got an error.
if ( is_wp_error( $googl_result ) ) {
return esc_url( $url );
}
$googl_result = json_decode( $googl_result['body'] );
$googl_link = $googl_result->id;
if ( $googl_link ) {
// Let's save that in post meta for the next call
add_post_meta( $post_id, '_tracked_googl_shortlink', $googl_link, true );
// And boom! return a short tracked URL.
return $googl_link;
} else {
return esc_url( $url );
}
// Final default, just in case
return esc_url( $url );
}
}
add_filter( 'sharing_permalink', 'jeherve_custom_sharedaddy_link', 10, 3 );
@AlexeyGonchar

This comment has been minimized.

Copy link

@AlexeyGonchar AlexeyGonchar commented Feb 6, 2017

Hi, Jeremy! Is there wordpress plugin for wordpress that make the same?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.