How can I set tab (only) if the product is in a certain category WooCommerce

爷,独闯天下 提交于 2019-12-10 15:55:37

问题


I have a tab set to add a tab which contains specifications in WooCommerce. I'd like to wrap it into an if statement to only set the tab if the product is part of a certain category.

add_filter( 'woocommerce_product_tabs', 'woo_custom_product_tabs' );

function woo_custom_product_tabs( $tabs ) {

    global $post;

    if ($product->is_category("Mobile Phones")) { 
        $tabs['custom_specification'] = array( 'title' => __( 'Specification', 'woocommerce' ), 'priority' => 50, 'callback' => 'woo_custom_specification_content' );
    }
}

What is the right code to check the category for WooCommerce in the if statements brackets?


回答1:


The conditional is_category() will return true if you are on a category archive page.

As you need a conditional for single product pages, you will target single product pages with is_product() conditional combined this way:

if ( is_product() && has_term( 'Mobile Phones', 'product_cat' ) ) {
    $tabs['custom_specification'] = array( 'title' => __( 'Specification', 'woocommerce' ), 'priority' => 50, 'callback' => 'woo_custom_specification_content' );
}

Or you could try also, in case, this one too:

if( is_product() && has_category( 'Mobile Phones' ) ) {
    $tabs['custom_specification'] = array( 'title' => __( 'Specification', 'woocommerce' ), 'priority' => 50, 'callback' => 'woo_custom_specification_content' );
}

@edit: You've missed return $tabs; at the end of your function before last closing bracket }.


References:

  • Remove product content based on category
  • How to check if a woocommerce product has any category assigned to it?



回答2:


Try below code. This code add woocommerce tab only when product has Mobile Phones category.

add_filter( 'woocommerce_product_tabs', 'woo_custom_product_tabs' );

    function woo_custom_product_tabs( $tabs ) {

      global $post;
     if ( is_product() && has_term( 'Mobile Phones', 'product_cat' )) 
     { 
      $tabs['custom_specification'] = array( 'title' => __( 'Specification', 'woocommerce' ), 'priority' => 50, 'callback' => 'woo_custom_specification_content' );
      }
      return $tabs;
    }


来源:https://stackoverflow.com/questions/38613769/how-can-i-set-tab-only-if-the-product-is-in-a-certain-category-woocommerce

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