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

咨询WP/WC实现访问首页时自动移除购物车指定商品的方案

代码问题分析

  • 你当前代码的判断条件is_page('54542')仅在访问ID为54542的独立页面时生效,如果你是要判断站点首页,更规范的写法是用is_front_page(),避免后续修改首页ID后功能失效。如果你的首页确实是固定ID为54542的页面,现有判断也可以生效,但兼容性较差。
  • 缺少WooCommerce依赖判断,若站点未启用WooCommerce、或购物车对象未初始化时,直接调用WC()->cart会触发致命错误。

优化后的可用代码

function remove_specified_product_from_cart_on_homepage() {
    // 仅在访问首页、且WooCommerce购物车对象存在时执行
    if ( is_front_page() && function_exists('WC') && ! is_null( WC()->cart ) ) {
        // 此处修改为你要移除的商品ID
        $target_product_id = 54542;
        $product_cart_id = WC()->cart->generate_cart_id( $target_product_id );
        $cart_item_key = WC()->cart->find_product_in_cart( $product_cart_id );
        if ( $cart_item_key ) {
            WC()->cart->remove_cart_item( $cart_item_key );
        }
    }
}
add_action( 'template_redirect', 'remove_specified_product_from_cart_on_homepage' );

注意事项

  • 如果你确实需要仅在访问ID为54542的特定页面时触发移除逻辑,把判断条件里的is_front_page()改回is_page( 54542 )即可,注意数字类型ID不要加引号,避免判断异常。
  • 若要移除多个指定商品,可以把$target_product_id改成数组,循环执行判断移除逻辑即可。
  • 代码建议放在主题的functions.php文件中,或自定义插件内,避免更新主题时被覆盖。

内容的提问来源于stack exchange,提问作者user6684898

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 10:54:04