Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

270
Views
How to add datalayer.push on WordPress functions.php?

I want to add datalayer.push on WordPress functions.php, I tried the following code but it throws an error, Uncaught Error: Call to a member function get_id() on string...

add_action('wp_head', 'datalayer_push');
function datalayer_push($product) {
    ?>
    <script>
        window.dataLayer = window.dataLayer || [];
        dataLayer.push({
            'itemId': '<?php echo $product->get_id(); ?>'
        });
    </script>
    <?php
}

How to implement the datalayer.push code properly on functions.php?

about 4 years ago · Santiago Trujillo
1 answers
Answer question

0

You've got an error because there's no $product variable in the wp_head by default. To make your code work, you have to rewrite it like this:

add_action('wp_head', 'datalayer_push');
function datalayer_push($product) {
    // Do not do anything if the current page is not a single product page
    if ( ! is_product() ) {
        return;
    }

    global $post;
    
    $product_id = $post->ID;
    $product = wc_get_product( $product_id );
    ?>
    <script>
        window.dataLayer = window.dataLayer || [];
        dataLayer.push({
            'itemId': '<?php echo $product->get_id(); ?>'
        });
    </script>
    <?php
}
about 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!