Woocommerce更新购物车项时order_review自定义模板未生效问题
解决方案
问题原因
WooCommerce 默认的模板查找逻辑只会优先读取主题目录下的woocommerce子目录内的自定义模板,不会主动扫描第三方插件的目录,因此AJAX调用woocommerce_order_review()时会加载官方默认模板。
解决方案1(全局生效,推荐)
通过woocommerce_locate_template过滤器修改模板查找优先级,让WooCommerce全局优先加载你插件内的order_review.php模板,AJAX请求也会自动生效:
add_filter( 'woocommerce_locate_template', 'custom_plugin_load_order_review_template', 10, 3 ); function custom_plugin_load_order_review_template( $template, $template_name, $template_path ) { // 仅匹配订单评论模板 if ( 'checkout/order_review.php' === $template_name ) { // 此处路径替换为你插件内模板的实际绝对路径 $plugin_template = plugin_dir_path( __FILE__ ) . 'woocommerce/checkout/order_review.php'; if ( file_exists( $plugin_template ) ) { return $plugin_template; } } return $template; }
将上述代码放入你插件的主文件中即可,不需要修改原有AJAX逻辑。
解决方案2(仅AJAX调用生效,无全局影响)
如果不需要全局替换模板,仅需要AJAX请求时加载自定义模板,可以直接修改你的AJAX逻辑,绕过原生woocommerce_order_review()的模板加载规则,手动引入自定义模板:
ob_start(); // 直接引入你插件内的自定义模板,路径替换为实际路径 include plugin_dir_path( __FILE__ ) . 'woocommerce/checkout/order_review.php'; $woocommerce_order_review = ob_get_clean(); // 后续原有逻辑保持不变 $response = array( 'cart_total' => WC()->cart->total, 'cart_item_key' => $new_key, 'fragments' => apply_filters( 'woocommerce_update_order_review_fragments', array( '.woocommerce-checkout-review-order-table' => $woocommerce_order_review, ) ), ); if ( ! empty( $data ) ) { $response['cartflows_data'] = $data; } return $response;
注意事项
- 代码中
plugin_dir_path( __FILE__ )的返回值为代码所在文件的目录路径,请根据你存放代码的文件位置调整路径,确保能正确指向自定义模板文件。
内容的提问来源于stack exchange,提问作者Hamayun Aziz
相关产品推荐
相关产品推荐

