簡體   English   中英

在 WooCommerce 的 HEAD 中包含一些 javascript 代碼收到訂單

[英]Include some javascript code in HEAD on WooCommerce Order received

目標:我需要在 Woocommerce 訂單確認頁面(購買后的頁面)上包含一個特定跟蹤的事件片段。 我必須將order_idcurrencytotal傳遞給跟蹤器。 這是我寫的代碼:

function wh_CustomReadOrder($order_id)
{
    //getting order object
    $order = wc_get_order($order_id);
    echo  "<script> gtag('event', 'conversion', { 'send_to': 'AW-995109926/CWeECK-epPYBEKbYwNoD', 'value': '".$order->get_total()."', 'currency': '".$order->currency."', 'transaction_id': '".$order_id."' }); </script>";
}
add_action('woocommerce_thankyou', 'wh_CustomReadOrder');

這包括頁面上正確的代碼並將相關信息傳遞給跟蹤器。 但是這段代碼並沒有出現在頁面的<head>中; 它出現在體內。 根據說明,此代碼必須放在<head>中。

我還沒有找到允許這種控制的片段插件。 還有另一種方法可以實現這一目標嗎?

如果我要在<head>的所有頁面上包含此代碼,但將其包裝在一個if語句中,該語句檢查 url、 /checkout/order-received/{order-id}/並在 true 時觸發,這是可能的還是還有其他方法嗎?

您可以使用以下內容將 Javascript 代碼注入“已收到訂單”頁面的頭部:

add_action( 'wp_head', 'wc_custom_redirect_after_purchase' );
function wc_custom_redirect_after_purchase() {
    if ( ! is_wc_endpoint_url('order-received') ) return;
    global $wp;

    // If order_id is defined
    if ( isset($wp->query_vars['order-received']) && absint($wp->query_vars['order-received']) > 0 ) :

    $order_id       = absint($wp->query_vars['order-received']); // The order ID
    $order          = wc_get_order($order_id ); // The WC_Order object
    
    $send_to        = 'AW-995109926/CWeECK-epPYBEKbYwNoD';
    $transaction_id = empty($order->get_transaction_id()) ? $order_id : $order->get_transaction_id(); // The transaction ID
    
    ?>
    <script type="text/javascript">
    gtag('event', 'conversion', {
        'send_to'       : '<?php echo $send_to; ?>', 
        'value'         : '<?php echo $order->get_total(); ?>', 
        'currency'      : '<?php echo $order->get_currency(); ?>', 
        'transaction_id': '<?php echo $transaction_id; ?>' 
    });
    </script>
    <?php
    endif;
}

代碼進入活動子主題(或活動主題)的functions.php文件。 它應該工作。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM