Jetpack

Jetpack: Add UTM Tracking to Sharing Buttons

Last updated 2 years ago

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 hlabs_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 ) );
 
        // Do not encode ampersands, GA doesn't like it.
        $tracked_url = str_replace( '&', '&', $tracked_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 = 'my_api_key';
 
        // 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', 'hlabs_custom_sharedaddy_link', 10, 3 );

Tags: #Google Analytics, #Jetpack, #Sharing

All code snippets are licensed GPLv2 or later unless otherwise stated.