Display different custom fields for different categories in WooCommerce

北慕城南 提交于 2020-01-06 04:19:22

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!