• Resolved s2am

    (@s2am)


    I would like to track in analytics how many people click on the sharing buttons. Normally I do it by using this line onclick=”ga(‘send’, ‘event’, ‘Button’, ‘Share’, ‘Twitter’);” is there any place where I can add this so it doesn’t get overwritten by the next update? Or any other idea how I can track the clicks?

Viewing 2 replies - 1 through 2 (of 2 total)
  • Plugin Author Robin Cornett

    (@littlerchicken)

    I did a quick test and have some code which should work. You can add this to your theme’s functions.php file or a place where you keep code snippets. Please make sure to practice safe coding and back up your files.

    The code is two parts. First, you have to tell WordPress you are okay with onclick tags in your link markup:

    
    add_filter( 'wp_kses_allowed_html', 'prefix_filter_allowed_html', 10 , 2 );
    /**
     * Prevent onclick events in URLs from being stripped by kses. 
     * @param $allowed
     * @param $context
     *
     * @return mixed
     */
    function prefix_filter_allowed_html( $allowed, $context ) {
    
    	if ( 'post' === $context ) {
    		$allowed['a']['onclick'] = true;
    	}
    
    	return $allowed;
    }
    

    Then you can actually modify the link output:

    
    add_filter( 'scriptlesssocialsharing_link_markup', 'prefix_modify_link_markup', 20, 2 );
    /**
     * Modify Scriptless link markup to include Analytics tracking.
     * 
     * @param $markup
     * @param $button
     *
     * @return string 
     */
    function prefix_modify_link_markup( $markup, $button ) {
    	$target  = 'email' === $button['name'] ? '' : ' target="_blank"';
    	$onclick = sprintf( 'onclick="ga(\'send\', \'event\', \'Button\', \'Share\', \'%s\');"', $button['label'] );
    
    	return sprintf(
    		'<a class="button %s"%s href="%s" rel="noopener" %s %s><span class="sss-name">%s</span></a>',
    		esc_attr( $button['name'] ),
    		$target,
    		esc_url( $button['url'] ),
    		$button['data'],
    		$onclick,
    		$button['label']
    	);
    }
    

    I only did a quick test of this locally so you will need to test and verify, but the link markup appeared to be correct. Hope this helps get you started.

    Thread Starter s2am

    (@s2am)

    Wow, that works ?? You’re awesome!

Viewing 2 replies - 1 through 2 (of 2 total)
  • The topic ‘Track Click as Event’ is closed to new replies.