Skip to content

Yoast’s Google Analytics for WordPress plugin rewrites links bug

So Yoast’s Google Analytics for WordPress plugin has a somewhat annoying “bug”, or oversight rather, where it rewrites relative link URLS to full URLs, including anchors. For example, <a href="#anchor"> becomes <a href="https://planetjon.ca/blah/#anchor">. There is more information about this on the wordpress forums.

Although prepending a relative anchor with the page’s URL is silly, it still does work correctly. However, the way the code is written you will lose any GET variables. If the page is dynamically generated, clicking on the anchor tag will refresh the page without the GET variables instead of scrolling to the anchor.

//Yoast's code, taken from googleanalytics.php in the plugin
function yoast_sanitize_relative_links( $content ) {
  preg_match( "|^http(s)?://([^/]+)|i", get_bloginfo( 'url' ), $match );
  $content = preg_replace( "/<a([^>]*) href=('|")/([^"']*)('|")/", "<a${1} href="" . $match[0] . "/" . "${3}"", $content );

//This is where the relative anchors are rewritten. Why, Joost, why?!
  if ( is_singular() ) {
    $content = preg_replace( "/<a([^>]*) href=('|")#([^"']*)('|")/", "<a${1} href="" . get_permalink() . "#" . "${3}"", $content );
  }
  return $content;
}

add_filter( 'the_content', 'yoast_sanitize_relative_links', 98 );
add_filter( 'widget_text', 'yoast_sanitize_relative_links', 98 );

Some workarounds that I have seen include adding a space before the anchor href like this <a href=" #anchor"> or wrapping another set of quotes around the anchor like this <a href="'#anchor'">. Hopefully these quick fixes will help, and hopefully Yoast will soon fix their code to not rewrite relative anchors.