WooCommerce按商品分类设置结账后自定义跳转不同感谢页的问题
代码问题诊断
你现有代码的核心错误是:跳转判断逻辑直接检查分类别名是否在你预定义的$product_categories固定数组中,该数组默认就包含两个目标分类,所以第一个分类的判断永远为真,永远只会触发第一个跳转规则,不会走到第二个分类的判断分支。同时你遍历订单商品时只标记了是否存在匹配分类,没有记录具体匹配到的分类,无法对应到不同跳转地址。
修复后完整代码
add_action( 'template_redirect', 'wc_custom_redirect_after_purchase' ); function wc_custom_redirect_after_purchase() { global $wp; // 仅在订单收到页触发 if ( is_checkout() && ! empty( $wp->query_vars['order-received'] ) ) { $order_id = intval( $wp->query_vars['order-received'] ); // 校验订单有效性 $order = wc_get_order( $order_id ); if ( ! $order ) { return; } // 定义分类与跳转地址的映射 $cat_redirect_map = array( 'asesoria-personalizada' => 'https://artchitectsproductions.com/gracias-compra-asesoria/', 'mezcla-y-mastering-online' => 'https://artchitectsproductions.com/gracias-compra-mezcla-y-mastering-online/' ); $matched_redirect = ''; // 遍历订单商品匹配分类 foreach( $order->get_items() as $item ){ $product_id = $item->get_product_id(); foreach ( $cat_redirect_map as $cat_slug => $redirect_url ) { if ( has_term( $cat_slug, 'product_cat', $product_id ) ) { $matched_redirect = $redirect_url; break 2; // 匹配到第一个分类后直接跳出所有循环,可根据需求调整优先级 } } } // 执行跳转 if ( ! empty( $matched_redirect ) ) { wp_redirect( $matched_redirect ); } else { wp_redirect( 'https://artchitectsproductions.com/gracias-por-tu-compra/' ); } exit; } }
说明
- 如果订单内同时存在两个分类的商品,会优先匹配排在
$cat_redirect_map数组前面的分类的跳转规则,你可以通过调整数组元素顺序修改优先级 - 替换了原代码中错误的中文弯引号,避免PHP语法报错
- 新增了订单有效性校验,避免无效订单ID触发异常
内容的提问来源于stack exchange,提问作者Pau Saez Lopez
相关产品推荐
相关产品推荐

