【问题标题】:Insert javascript code into the head tags of the woocommerce thank you page将 javascript 代码插入到 woocommerce 感谢页面的头部标签中
【发布时间】:2019-09-30 08:38:00
【问题描述】:

我正在尝试将一些谷歌跟踪脚本添加到我的感谢页面。我已经编写了这段代码,它成功地将跟踪器注入到带有动态值的谢谢中,但我需要将它添加到标签中。

function mv_google_conversion( $order_id ) {
    $order = new WC_Order( $order_id );
    $currency = $order->get_currency();
    $total = $order->get_total();
    ?>
    <script>
      gtag('event', 'conversion', {
          'send_to': 'AW-746876528/x5W1CLfA8JoBEPDckeQC',
          'value': <?php echo $total; ?>,
          'currency': '<?php echo $currency; ?>',
          'transaction_id': '<?php echo $order_id; ?>'
      });
    </script>
    <?php
  }
  add_action( 'woocommerce_thankyou', 'mv_google_conversion' );

我将如何使用此代码以及 header.php 中的动态值,或者是否有针对 woocommerce 感谢页面上的标签的挂钩。

【问题讨论】:

    标签: javascript php wordpress woocommerce orders


    【解决方案1】:

    您将使用以下代码在“已收到订单”(谢谢)页面的头部标签上注入代码:

    add_action( 'wp_head', 'my_google_conversion' );
    function my_google_conversion(){
        // On Order received endpoint only
        if( is_wc_endpoint_url( 'order-received' ) ) :
    
        $order_id = absint( get_query_var('order-received') ); // Get order ID
    
        if( get_post_type( $order_id ) !== 'shop_order' ) return; // Exit
    
        $order = wc_get_order( $order_id ); // Get the WC_Order Object instance
        ?>
        <script>
          gtag('event', 'conversion', {
              'send_to': 'AW-746876528/x5W1CLfA8JoBEPDckeQC',
              'value': <?php echo $order->get_total(); ?>,
              'currency': '<?php echo $order->get_currency(); ?>',
              'transaction_id': '<?php echo $order_id; ?>'
          });
        </script>
        <?php   
        endif;
    }
    

    代码在您的活动子主题(或活动主题)的functions.php 文件中。经过测试并且可以工作。

    【讨论】:

    • 我们如何在&lt;head&gt; 中进一步向下移动?它目前位于实际的 Google Ads 全局网站代码之前。
    • @Garconis 你忘记了钩子优先级(默认为 10),所以你需要用更大的数字来指定它,比如 90000 所以在代码中: add_action( 'wp_head', 'my_google_conversion', 90000 );... 或者您也可以使用 wp_footer 挂钩,而不是 wp_head.... 现在应该位于 Google Ads 全局网站代码之后。如果可行,您可以投票赞成这个答案。
    猜你喜欢
    • 2018-03-12
    • 1970-01-01
    • 2018-11-05
    • 1970-01-01
    • 2023-03-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多