如何在wp_head中获取WooCommerce订单信息
解决WooCommerce订单接收页wp_head中输出跟踪像素的问题
问题原因
你之前的testpixel代码失败,核心原因是**$order_id变量未定义**:
wp_head钩子本身不会传递订单ID参数,无法直接获取订单对象;- 订单接收页的订单ID通过URL中的
order-received参数传递,需要主动从URL中提取。
解决方案
直接从URL参数中获取订单ID,验证有效性后获取订单对象,再替换跟踪像素中的变量并输出到wp_head。
完整可行代码
function testpixel() { // 判断当前是否为WooCommerce订单接收页 if ( is_wc_endpoint_url( 'order-received' ) ) { // 从URL参数中提取订单ID并转为整数 $order_id = absint( get_query_var( 'order-received' ) ); // 验证订单ID有效性并获取订单对象 if ( $order_id && ( $order = wc_get_order( $order_id ) ) ) { $order_total = $order->get_total(); // 构建跟踪像素代码,用esc_attr转义变量避免安全问题 $pixel_code = '<!-- Conversion Pixel for [misc]- DO NOT MODIFY --><img src="https://data.adxcel-ec2.com/pixel/?ad_log=referer&action=misc&value=' . esc_attr( $order_total ) . '&order_id=' . esc_attr( $order_id ) . '&xxxxxxxxxxxxxx" width="1" height="1" border="0"><!-- End of Conversion Pixel -->'; echo $pixel_code; } } } add_action( 'wp_head', 'testpixel' );
关键说明
get_query_var('order-received'):专门用于提取订单接收页URL中的订单ID参数;absint():确保订单ID是正整数,过滤非法值;esc_attr():对订单ID和总额进行转义,防止XSS注入,符合WordPress安全规范;- 增加订单对象有效性判断,避免因无效订单ID导致的代码报错。
内容的提问来源于stack exchange,提问作者GrimesWeb
相关产品推荐
相关产品推荐

