![](/img/trans.png)
[英]Set order id and order total in a javascript on Woocommerce order received
[英]Include some javascript code in HEAD on WooCommerce Order received
目标:我需要在 Woocommerce 订单确认页面(购买后的页面)上包含一个特定跟踪的事件片段。 我必须将order_id
、 currency
和total
传递给跟踪器。 这是我写的代码:
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.