简体   繁体   English

如何在 WordPress 函数.php 上添加 datalayer.push?

[英]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...我想在 WordPress 函数上添加 datalayer.push。php,我尝试了以下代码但它抛出错误,未捕获错误:调用字符串上的成员 function get_id()...

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?如何在 functions.php 上正确实现 datalayer.push 代码?

You've got an error because there's no $product variable in the wp_head by default.你有一个错误,因为默认情况下wp_head中没有 $product 变量。 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
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM