• An external link with an existing onclick value can become corrupted by Google Analytics for WordPress. My fix is below:

    I have a datafeedr banner ad on my site which has a pageTracker._trackPageview() already set in the onclick so that I can track outbound clicks on this ad. The ad links to an external site, so Google Analytics for WordPress tags it as an outbound “article” link. Then when it merges the two onclicks into one string, the first single quote of my existing _trackPageview() value is replaced by a double-quote, breaking the javascript call.

    I tracked it down to line 474 of the GA_Filter::ga_parse_link() function in googleanalytics.php.

    Printing the $matches[4] value prior to the preg_replace() action displays this:
    onclick="javascript:pageTracker._trackPageview('/bannerads/snowferno/snowferno_banner_1_468x60.png');"

    After the preg_replace() action of line 474, $matches[4] equals this (notice the lone double-quote before /bannerads prematurely terminating the onclick):
    onclick="javascript:pageTracker._trackPageview('/outbound/article/snowferno.com'); javascript:pageTracker._trackPageview("/bannerads/snowferno/snowferno_banner_1_468x60.png');"

    I believe the regex pattern '/onclick=[\'\"](.*?)[\'\"]/i' was confused by the single-quote in my onclick. Terminating too soon, or replacing multiple times? I’m not exactly sure, but…

    My proposed fix is to split the preg_replace into two calls, one for ‘onclick’ actions in $matches[4] surrounded by single-quotes, and another for double-quotes. Because $coolBit was built with single-quotes already, you need to swap the single- and double-quotes.

    Line 474 is replaced by these two lines:
    $matches[4] = preg_replace('/onclick=[\'](.*?)[\']/i', 'onclick=\'' . str_replace(array('"', "'"), array("'",'"'), $coolBit) .' $1\'', $matches[4]);
    $matches[4] = preg_replace('/onclick=[\"](.*?)[\"]/i', 'onclick="' . $coolBit .' $1"', $matches[4]);

    This was a quick-fix solution for me. Anyone who knows this plugin better, improvements are welcome.

  • The topic ‘[Plugin: Google Analytics for WordPress] Single/Double Quote error if merging with existing onclick’ is closed to new replies.