问题
I am trying to display different custom fields for different categories in WooCommerce.
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' );
}
But this isn't working for me.
Is there any better way to rectify this issue?
Thanks.
回答1:
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
}
....
It looks like you are trying to override content-single-product.php
template.
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
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
}
};
来源:https://stackoverflow.com/questions/38759654/display-different-custom-fields-for-different-categories-in-woocommerce