可能有不止一种方法可以做到这一点,但他们都改变了在包含模板之前过滤模板的想法。
您可以完全跳过 WooCommerce 的 simple-product.php 模板(无需覆盖该模板)并直接转到 simple-product-mock.php 并在那里创建所有内容。你可以通过过滤template_include来做到这一点。
add_filter( 'template_include', 'so_25789472_template_include' );
function so_25789472_template_include( $template ) {
if ( is_singular('product') && (has_term( 'mock', 'product_cat')) ) {
$template = get_stylesheet_directory() . '/woocommerce/single-product-mock.php';
}
return $template;
}
您可以编辑single-product-mock.php 以调用content-single-product-mock.php 并硬编码那个 文件。没有什么需要你继续使用 Woo 的钩子和函数。它们的目的只是让您轻松定制。
或者更棘手的是,您可以将 single-product/title.php 等模板复制到 single-product-mock 文件夹中...例如:single-product-mock/title.php 然后任何时候我们在模拟类别中的单个产品模板上,我们'将拦截对single-product/something.php模板的调用并将它们重定向到single-product-mock/something.php 如果它存在,如果它不存在则继续指向single-product/something.php。我们将通过woocommerce_locate_template 过滤器完成此操作。
add_filter( 'woocommerce_locate_template', 'so_25789472_locate_template', 10, 3 );
function so_25789472_locate_template( $template, $template_name, $template_path ){
// on single posts with mock category and only for single-product/something.php templates
if( is_product() && has_term( 'mock', 'product_cat' ) && strpos( $template_name, 'single-product/') !== false ){
// replace single-product with single-product-mock in template name
$mock_template_name = str_replace("single-product/", "single-product-mock/", $template_name );
// look for templates in the single-product-mock/ folder
$mock_template = locate_template(
array(
trailingslashit( $template_path ) . $mock_template_name,
$mock_template_name
)
);
// if found, replace template with that in the single-product-mock/ folder
if ( $mock_template ) {
$template = $mock_template;
}
}
return $template;
}
改为过滤wc_get_template。
/**
* Change wc template part for product with a specific category
*
* @param string $templates
* @param string $slug
* @param string $name
* @return string
*/
function so_25789472_get_template_part( $template, $slug, $name ) {
if ( $slug == 'content' && $name = 'single-product' && has_term( 'test', 'product_cat' ) ) {
$template = locate_template( array( WC()->template_path() . 'content-single-product-test.php' ) );
}
return $template;
}
add_filter( 'wc_get_template_part', 'so_25789472_get_template_part', 10, 3 );