问题描述
我试图在WooCommerce中为不同类别显示不同的自定义字段。
I am trying to display different custom fields for different categories in WooCommerce.
我在content-single-product.php模板文件中使用了以下条件语句:
I have used the following conditional statement in content-single-product.php template file:
if(is_product_category('categoryname'))
{
// display my customized field
}
else
{
do_action( 'woocommerce_after_single_product_summary' );
}
但这对我不起作用。
有没有更好的方法来纠正此问题?
Is there any better way to rectify this issue?
谢谢。
推荐答案
条件is_product_category()不起作用在单个产品模板中为您服务。在这种情况下,正确的条件是两个条件的组合:
The condition is_product_category() will not work for you in single product templates. The correct conditions are a combination of two in this case:
if ( is_product() && has_term( 'categoryname', 'product_cat' ) ) {
// display my customized field
}
....
您似乎要覆盖 content-single-product.php
模板。
It looks like you are trying to override content-single-product.php
template.
移动 woocommerce_single_product_summary
并不是一个很好的主意,如果您不想显示 'categoryname'
产品的3个挂钩函数:
Moving woocommerce_single_product_summary
hook inside your ELSE statement is not a very good idea, only if you don't want to display for 'categoryname'
product that 3 hooked functions:
* @hooked woocommerce_output_product_data_tabs - 10
* @hooked woocommerce_upsell_display - 15
* @hooked woocommerce_output_related_products - 20
您可以嵌入代码(在活动子主题或主题的function.php文件上)(而不是此处的覆盖模板)在钩子函数中使用这2个钩子中的更方便的钩子:
Instead (of overriding templates here) you could embed your code (on function.php file of your active child theme or theme) in a hooked function using the more convenient of this 2 hooks:
//In hook 'woocommerce_single_product_summary' with priority up to 50.
add_action( 'woocommerce_single_product_summary', 'displaying_my_customized_field', 100);
function displaying_my_customized_field( $woocommerce_template_single_title, $int ) {
if ( is_product() && has_term( 'categoryname', 'product_cat' ) ) {
// echoing my customized field
}
};
OR
// In hook 'woocommerce_after_single_product_summary' with priority less than 10
add_action( 'woocommerce_after_single_product_summary', 'displaying_my_customized_field', 5);
function displaying_my_customized_field( $woocommerce_template_single_title, $int ) {
if ( is_product() && has_term( 'categoryname', 'product_cat' ) ) {
// echoing my customized field
}
};
这篇关于在WooCommerce中显示不同类别的不同自定义字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!