我正试图在order-received 进行再营销的页面dataLayer. 脚本必须放入<head> html代码的一节。我怎样才能得到$order 在<head> 部分
我可以得到$order_id 在里面woocommerce_thankyou 但不在wp_head
function tracking_thank_you_page( $order_id ) {
?>
<script>
console.log( \'order_id: <?php echo $order_id; ?>\' );
</script>
<?php
}
add_action( \'woocommerce_thankyou\', \'tracking_thank_you_page\' );
我有
$order_id 使用上述代码。
function tracking_in_head( $order_id ) {
?>
<script>
console.log( \'order_id: <?php echo $order_id; ?>\' );
</script>
<?php
}
add_action( \'wp_head\', \'tracking_in_head\' );
我没有访问
$order_id 在
wp_head更新:在收到Hector有用的回复后,我编辑了我的代码。它创建javascriptdataLayer 产品SKU:
function tracking_in_head() {
$product_skus = \'\';
global $wp_query;
if( !empty( $wp_query->query_vars[ \'order-received\' ] ) ) {
$order = wc_get_order( $wp_query->query_vars[ \'order-received\' ] );
$items = $order->get_items();
echo "<script>
dataLayer = [];
dataLayer.push({
\'event\': \'purchase\',
";
if( !empty( $items ) ) {
echo "\'items\': [";
foreach( $items as $item ) {
$product = wc_get_product( $item[ \'product_id\' ] );
echo "{
\'id\': \'" . $product->get_sku() . "\',
\'google_business_vertical\': \'retail\'
},";
}
echo "]";
}
echo "});
</script>";
}
}
add_action( \'wp_head\', \'tracking_in_head\' );
这个代码有什么需要改进的吗?
SO网友:Hector
让我们检查两个挂钩。这个woocommerce_thankyou 挂钩已添加到line 80 of thankyou.php 文件钩子越来越大$order->get_id() 作为论据。因此,当您钩住woocommerce_thankyou 在您的第一个示例中。
但是wp_head 正在从加载的操作wp_head() function 没有任何争论。因此,在第二段中,您没有任何$order_id 变量
如果你想得到订单head 部分中,您可能需要使用WooCommerce函数来获取订单,然后在head.
示例:
function tracking_in_head() {
// Get needed data here.
$all_orders = wc_get_orders();
// Check https://docs.woocommerce.com/wc-apidocs/source-function-wc_get_order.html to see WC order functions.
?>
<script>
console.log( \'order_id: <?php echo $order_id; ?>\' );
</script>
<?php
}
add_action( \'wp_head\', \'tracking_in_head\' );