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

如何修改PHP代码,访问指定父页面子页面时清空WooCommerce购物车

解决WooCommerce访问指定父页面子页面时自动清空购物车的问题

你的问题在于$post->post_parent返回的是父页面的ID而非slug,直接对比字符串自然不会生效。以下是修改后的代码,能实现访问mtm-user的所有子页面时自动清空购物车:

add_action( 'template_redirect', 'woocommerce_clear_cart_on_parent_child_pages' );
function woocommerce_clear_cart_on_parent_child_pages() {
    // 仅在页面类型下执行逻辑
    if ( ! is_page() || ! isset( $GLOBALS['post'] ) ) {
        return;
    }

    global $post;
    $target_parent_slug = 'mtm-user';
    $parent_page_id = $post->post_parent;

    // 可选:如果需要访问mtm-user本身时也清空购物车,保留以下代码块
    if ( $post->post_name === $target_parent_slug ) {
        WC()->cart->empty_cart();
        return;
    }

    // 检查当前页面是否是mtm-user的子页面
    if ( $parent_page_id > 0 ) {
        $parent_page = get_post( $parent_page_id );
        if ( $parent_page && $parent_page->post_name === $target_parent_slug ) {
            WC()->cart->empty_cart();
        }
    }
}

代码说明:

  • 用is_page()限制逻辑仅在页面类型生效,避免影响产品、文章等其他内容页面
  • 使用WC()->cart替代global $woocommerce,这是WooCommerce官方推荐的调用方式,更简洁高效
  • 通过get_post($parent_page_id)获取父页面对象,再对比其post_name(即slug)来判断是否符合条件
  • 保留了访问mtm-user本身时清空购物车的逻辑,若不需要可直接删除对应的if块

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 15:20:32