WooCommerce店铺子页面自定义page-{slug}.php模板不生效问题
失效原因
WooCommerce 会强制接管店铺页及其所有子级页面的模板路由,优先级高于 WordPress 原生页面模板规则,因此你按照原生规则命名的 page-{slug}.php、page-{id}.php 模板会被WooCommerce默认的商城模板覆盖,无法正常加载。
解决方案
通过 template_include 过滤器手动提升自定义模板的优先级即可解决,操作步骤如下:
- 确认你的自定义模板
page-featured-products.php已经存放在当前激活的主题(或子主题,推荐优先使用子主题避免后续主题更新覆盖自定义内容)根目录下 - 打开当前主题的
functions.php文件,添加如下代码片段:
add_filter( 'template_include', 'assign_custom_featured_products_template' ); function assign_custom_featured_products_template( $original_template ) { // 可替换为页面ID,比如is_page(123),匹配更稳定 if ( is_page( 'featured-products' ) ) { $custom_template_path = locate_template( 'page-featured-products.php' ); if ( $custom_template_path ) { return $custom_template_path; } } return $original_template; }
- 保存文件后刷新目标页面,自定义模板即可正常生效
如果后续需要给多个WooCommerce店铺子页面配置自定义模板,可以用批量判断的代码:
add_filter( 'template_include', 'batch_assign_shop_child_page_templates' ); function batch_assign_shop_child_page_templates( $original_template ) { // 按需求添加需要自定义模板的页面slug $target_page_slugs = [ 'featured-products', 'best-sellers', 'limited-offers' ]; if ( is_page( $target_page_slugs ) ) { $current_slug = get_queried_object()->post_name; $custom_template_path = locate_template( "page-{$current_slug}.php" ); if ( $custom_template_path ) { return $custom_template_path; } } return $original_template; }
内容的提问来源于stack exchange,提问作者avappjanaawdtidcqk
相关产品推荐
相关产品推荐

