You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在WooCommerce结账页而非订单完成页加载指定JS脚本?

解决WooCommerce仅在结账页加载脚本,排除订单完成页的问题

嘿,这个问题我之前做WooCommerce项目时也碰到过!你当前的代码用get_query_var('pagename') === 'checkout'来判断,但订单完成页作为结账页的子端点页面,它的pagename会关联父页面slug,导致你的条件误触发,脚本在无表单的订单完成页加载后报错。

下面给你两种靠谱的解决方法:

方法一:用WooCommerce专属条件函数(推荐)

WooCommerce提供了专门的条件判断函数,既准确又省心。is_checkout()会识别所有结账相关页面,我们可以搭配is_wc_endpoint_url('order-received')排除订单完成页:

if ( is_checkout() && !is_wc_endpoint_url('order-received') ) {
    wp_enqueue_script('script', 'my.js', array('jquery'), 1.1, true);
}

原理说明:

  • is_checkout():判断当前页面是否属于WooCommerce结账体系(包括主结账页和子端点页)
  • is_wc_endpoint_url('order-received'):检测当前是否是订单完成的端点页面,加上!就表示排除这个页面

这种方法不受 permalink 设置影响,WooCommerce版本更新后也能稳定工作,是最推荐的方案。

方法二:基于查询变量的严格判断

如果你更习惯用get_query_var的方式,可以同时检查pagename和订单完成的专属查询参数:

$current_pagename = get_query_var('pagename');
$order_received_id = get_query_var('order-received');

// 确保是结账页,且没有订单完成的参数
if ( $current_pagename === 'checkout' && empty($order_received_id) ) {
    wp_enqueue_script('script', 'my.js', array('jquery'), 1.1, true);
}

或者也可以直接检查是否存在端点:

if ( get_query_var('pagename') === 'checkout' && !is_wc_endpoint_url() ) {
    wp_enqueue_script('script', 'my.js', array('jquery'), 1.1, true);
}

原理说明:

订单完成页会自动携带order-received的查询变量,只要这个变量为空,就说明当前是主结账页而非子端点页。

内容的提问来源于stack exchange,提问作者j.c

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.28 09:51:11