Use code BLACKFRIDAY through Dec. 2nd for 30% off!
  1. Home
  2. Docs
  3. General
  4. How to track share button clicks (reporting)

How to track share button clicks (reporting)

Currently, we don’t have reporting in Novashare for performance reasons. However, this doesn’t mean you can’t track your share button stats/clicks. If you use an analytics tool on your site that supports click events (which almost all do), you should be able to add an event to your share buttons. In most cases, this lets you see which buttons are clicked and on which URLs.

Below are a few examples.

How to track shares with Google Analytics

This PHP code snippet utilizes our novashare_button_attributes filter and Google Analytics events (set up GA events, GA4 share event reference).

add_filter('novashare_button_attributes', function($attributes, $network, $location) {

    //the "more networks" button only opens the share window
    if($network === 'share') {
        return $attributes;
    }

    //normalize block-{id} locations
    if(strpos($location, 'block-') === 0) {
        $location = 'block';
    }

    //the URL being shared, falls back to the current page
    $url = (is_singular() || in_the_loop()) ? get_permalink() : '';

    $js = sprintf(
        'var p={method:%1$s,content_type:%2$s,item_id:%3$s||location.href};typeof gtag==="function"?gtag("event","share",p):(window.dataLayer=window.dataLayer||[]).push(Object.assign({event:"share"},p));',
        wp_json_encode($network),
        wp_json_encode($location),
        wp_json_encode($url)
    );

    //copy and print already have an onClick, and browsers ignore a duplicate attribute
    $event = in_array($network, array('copy', 'print'), true) ? 'onmouseup' : 'onclick';

    $attributes[$event] = esc_attr($js);

    return $attributes;
}, 10, 3);

How to track shares with Fathom Analytics

This PHP code snippet utilizes our novashare_button_attributes filter and Fathom Analytics link clicks.

add_filter('novashare_button_attributes', function($attributes, $network, $location) {

    //the "more networks" button only opens the share window
    if($network === 'share') {
        return $attributes;
    }

    //normalize block-{id} locations
    if(strpos($location, 'block-') === 0) {
        $location = 'block';
    }

    //event name, e.g. "Share: facebook (inline)"
    $event_name = 'Share: ' . $network . ' (' . $location . ')';

    $js = sprintf(
        'window.fathom&&fathom.trackEvent(%s);',
        wp_json_encode($event_name)
    );

    //copy and print already have an onClick, and browsers ignore a duplicate attribute
    $event = in_array($network, array('copy', 'print'), true) ? 'onmouseup' : 'onclick';

    $attributes[$event] = esc_attr($js);

    return $attributes;
}, 10, 3);

Related Articles