WooCommerce不加载自定义模板求助(Sage 10环境)
核心原因
Sage 10 采用 Blade 模板引擎,主题结构和传统 WordPress 主题差异较大,WooCommerce 默认的模板加载规则无法直接识别 resources/views/woocommerce 目录下的文件。原生 WooCommerce 会优先查找主题根目录下的 woocommerce 文件夹,但 Sage 10 的视图文件集中在 resources/views 内,必须手动配置模板路径或适配 Blade 语法才能让自定义模板生效。
具体解决步骤
确认模板路径与文件名
自定义模板需放在resources/views/woocommerce下,文件名和子目录结构必须和plugins/woocommerce/templates内的文件完全一致,比如要修改商品详情页,需创建resources/views/woocommerce/single-product.php(或 Blade 格式的.blade.php文件),子模板如加入购物车按钮则对应single-product/add-to-cart/simple.php。注册 Sage 视图路径到 WooCommerce
在主题的app/Providers/AppServiceProvider.php或functions.php中添加以下代码,让 WooCommerce 优先查找 Sage 的视图目录:add_filter('woocommerce_locate_template', function($template, $template_name, $template_path) { $sage_template = resource_path('views/woocommerce/' . $template_name); if (file_exists($sage_template)) { return $sage_template; } return $template; }, 10, 3);适配 Blade 模板语法(可选)
如果想用 Blade 编写模板,需将文件后缀改为.blade.php,同时调整上述过滤器代码:add_filter('woocommerce_locate_template', function($template, $template_name, $template_path) { $blade_template_name = str_replace('.php', '.blade.php', $template_name); $sage_template = resource_path('views/woocommerce/' . $blade_template_name); if (file_exists($sage_template)) { return $sage_template; } return $template; }, 10, 3);清除 Sage 缓存
Sage 10 会缓存编译后的 Blade 模板,修改模板后需手动删除storage/framework/views目录下的所有文件,或通过 WordPress 后台的 Sage 工具(若有)清除缓存。确认主题已声明 WooCommerce 支持
检查app/setup.php中是否存在以下代码,确保主题已开启 WooCommerce 支持:add_action('after_setup_theme', function() { add_theme_support('woocommerce'); // 可选:启用商品图库的缩放、灯箱、滑动功能 add_theme_support('wc-product-gallery-zoom'); add_theme_support('wc-product-gallery-lightbox'); add_theme_support('wc-product-gallery-slider'); });
内容的提问来源于stack exchange,提问作者Justina

