Take the GA code from your header and wrap it in a function hooked to wp_head
;
function __analytics_head()
{
$options = get_option( 'themename_theme_options' );
if ( !empty( $options['analytics'] ) ) :
?>
<script type="text/javascript">
var _gaq = _gaq || [];
_gaq.push(['_setAccount', '<?php echo esc_js( $options['analytics'] ) ; ?>']);
_gaq.push(['_trackPageview']);
(function() {
var ga = document.createElement('script'); ga.type="text/javascript"; ga.async = true;
ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();
</script>
<?php
endif;
}
add_action( 'wp_head', '__analytics_head', 100 );
Obviously, this is only guideline code – the way you retrieve your options may vary – but the idea is to check if a GA account has been set, and if so, proceed to print the script.