skip to Main Content

I have i one template file call abc.php and using this template only for 1 page now i want to add google conversion tracking code in section. If i add code before get_header(); function then it shows before tag and if i put after get_header(); then it shows in tag.

Please help me as i want to use conversion code only for 1 particular page so i can’t add this code in header.php

 <?php
  /* Template Name: Cost_Estimation_Result */ 
  ?>
   <!-- Event snippet for Website lead conversion page -->
   <script>
    gtag('event', 'conversion', {'send_to': '*********************'});
   </script>
   <?php
   get_header();
   ?>

2

Answers


  1. Chosen as BEST ANSWER

    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>';
        } 
      }
    

  2. 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

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search