php - how to add google analytics code in template
Solution:
Add this javascript
var script = document.createElement("script");
script.innerHTML = "your analytics code";
// Append to head
document.head.appendChild(script);
try this not sure if it will work though , another way if u get string from get_header() and append gtag part before loading in your page like this :
$header = str_get_html(get_header());
$gtag = "<script>
gtag('event', 'conversion', {'send_to': '*********************'});
</script>";
$header->find('head', 0)->innertext = $gtag.$header->find('head', 0)->innertext;
reference https://stackoverflow.com/a/18187111/8719734
Answer
Solution:
Add Below code in function.php solved my problem.
add_action( 'wp_head', 'wpsites_add_tracking_code' );
function wpsites_add_tracking_code() {
if ( is_page(200) ) {
echo'<div class="tracking-code">add your tracking code here.</div>';
}
}
Source