use*_*251 9 php wordpress woocommerce
你好我对woocommerce相当新,我的商店有四类产品使用相同的单一产品模板.我想添加第五类产品,其中产品页面布局与已使用的产品页面布局非常不同.
这是文件结构 -
我创建了一个名为content-single-product-mock.php的文件.在single-product.php中使用以下代码
<?php if (has_term( 'mock', 'product_cat' )) {
woocommerce_get_template_part( 'content', 'single-product-mock' );
} else{
wc_get_template_part( 'content', 'single-product' );
} ?>
Run Code Online (Sandbox Code Playgroud)
对于类别mock,它重定向到content-single-product-mock.php,但它使用单产品文件夹中的模板文件.如何更改content-single-product-mock.php中的模板路径,以便它使用single-product-mock文件夹中的自定义文件?
hel*_*ing 15
可能有不止一种方法可以做到这一点,但它们都会转变在包含模板之前过滤模板的想法.
您可以完全跳过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;
}
Run Code Online (Sandbox Code Playgroud)
您可以编辑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;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
8812 次 |
| 最近记录: |