Put Google Experiment Code Higher in the Header in WordPress

To get Google Experiment Code working you need to get it higher in the WordPress head above the regular Google GA code. If you have used a plugin to insert the Google GA code there may be no control on whereabouts the code can be placed or adjusted in priority, for example Yoast Google Analytics plugin has no user maneuverability.

You can inject this code higher into your WordPress header using a WordPress hook with a high priority in your themes functions.php file.

//Google Experiment Code
function google_experiment_code() {
	if( is_page(4164) ) {
	?>
<!-- Google Analytics Content Experiment code -->
<script>function utmx_section(){}function utmx(){}(function(){var
k='54437798-4',d=document,l=d.location,c=d.cookie;
if(l.search.indexOf('utm_expid='+k)>0)return;
function f(n){if(c){var i=c.indexOf(n+'=');if(i>-1){var j=c.
indexOf(';',i);return escape(c.substring(i+n.length+1,j<0?c.
length:j))}}}var x=f('__utmx'),xx=f('__utmxx'),h=l.hash;d.write(
'<sc'+'ript src="'+'http'+(l.protocol=='https:'?'s://ssl':
'://www')+'.google-analytics.com/ga_exp.js?'+'utmxkey='+k+
'&utmx='+(x?x:'')+'&utmxx='+(xx?xx:'')+'&utmxtime='+new Date().
valueOf()+(h?'&utmxhash='+escape(h.substr(1)):'')+
'" type="text/javascript" charset="utf-8"></sc'+'ript>')})();
</script><script>utmx('url','A/B');</script>
<!-- End of Google Analytics Content Experiment code -->

	<?php
	}
}
add_action( 'wp_head','google_experiment_code', 5 );

Breaking this down a bit, a function is created and conditionally set to appear on a certain post/page by using an if statement. The PHP tag is then closed so all the Google javascript code can be entered, then the PHP is opened again after the code.

Finally the action wp_head will run this function with a priority of 5 which will place it above the Yoast Google Analytics code, you could run it even higher by using a lower number but make sure important SEO tags are kept first in the pecking order.