【发布时间】:2017-09-23 01:55:58
【问题描述】:
我整天都在扯头发,请原谅简短的描述,我只需要验证我的理智!!
正如标题所说,我正在尝试在 woocommerce 中创建两个或三个不同的单一产品布局。最低要求是拥有多个单一产品文件夹,每个文件夹都有自己的名称和配置。
无论我尝试以哪种方式覆盖 single-product.php 并使该文件使用逻辑来检查 product_cat 并相应地给出模板,我要么页面未加载,要么我写的内容被跳过并使用默认值已加载。
到目前为止,我已经多次通过以下方法,试图将可能过时的代码拼凑在一起,否则会引起大惊小怪:
WooCommerce - How to create multiple single product template based on category?
Woocommerce single product - template by categories
Creating a different template file for certain Product Categories - Wordpress/Woocommerce?
我更希望有人可能知道一些我显然错过的东西,因为那里有很多关于尝试什么的文章,大多数都声称成功,但我无法这样做。
[更新] 使用来自@helgatheviking 的template_include 代码
目前还没有成功,但这是我要做的;
文件结构 team-shops 是我想要获得的类别
- /mytheme/woocommerce/single-product.php - 没有变化
- /mytheme/woocommerce/content-single-product.php
- /mytheme/woocommerce/single-product-team-shops.php - 将第 37 行更改为
<?php wc_get_template_part( 'content', 'single-product-team-shops' ); ?> - /mytheme/woocommerce/content-single-product-team-shops.php - 在#product-id 中添加了额外的 id(第 39 行)
- /mytheme/woocommerce/single-product-team-shops/ 文件夹,其中包含要更改的所有单个产品文件。
正如我上面所说,这不起作用,但希望通过我提供的内容,问题可能会更加明显。
再次感谢您的帮助:)
[想我明白了]
好的,所以我认为我有一些有用的东西,至少目前看来,还有一些进一步的测试要做,但任何想法都非常受欢迎,这就是我到目前为止所拥有的一个 -我的主题中的 product-team-shops 文件夹
add_filter( 'woocommerce_locate_template', 'so_25789472_locate_template', 10, 3 );
function so_25789472_locate_template( $template, $template_name, $template_path ){
$term_id = 2854;
$taxonomy_name = 'product_cat';
$term_children = get_term_children( $term_id, $taxonomy_name );
foreach ( $term_children as $child ) {
// on single posts with mock category and only for single-product/something.php templates
if( is_product() && has_term( $child, '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-team-shops/", $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;
}
【问题讨论】:
-
我想说这听起来非常熟悉,但我的答案在你的第一个链接here。我的
template_include方法应该可以让您开始使用多个单一产品模板。它看起来并不过时(尽管我现在无法重新测试它),所以请分享您的代码版本并说明您将模板存储在哪里。 -
感谢@helgatheviking 我会根据您的链接进行所有设置并回复您,感谢您与我们联系!
-
更新@helgatheviking
-
嘿,@helgatheviking 另一个更新,上面的代码确实有效,但是,只影响 content-single-product.PHP,请原谅我在这里的无知。但是,您建议的第二种方法效果很好,因此我目前已启动并运行该方法。我使用这种方法遇到的唯一问题是“has_term”不允许我使用父母,到目前为止我一直在尝试使用“get_term_children”但没有成功,我会尽快更新该代码,谢谢再次:)
-
如果您在
content-single-product-custom.php中使用相同的动作挂钩,您将获得与默认custom-single-product.php相同的外观。
标签: php wordpress woocommerce logic