Home > Software engineering >  How to add datalayer.push on WordPress functions.php?
How to add datalayer.push on WordPress functions.php?

Time:07-26

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?

CodePudding user response:

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
}
  • Related