Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

276
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda