简体   繁体   English

将自定义字段添加到特定类别的 woocommerce 产品

[英]Add Custom field to woocommerce product for an specific category

I am trying to add a custom field "Color" to my woocommerce orders but this custom field has to be in a few specific categories, let's say category "ballons", so the code inside functions.php is this:我正在尝试向我的 woocommerce 订单添加一个自定义字段“颜色”,但这个自定义字段必须属于几个特定类别,比如说“气球”类别,所以functions.php 中的代码是这样的:

add_action('woocommerce_before_add_to_cart_button','wdm_add_custom_fields');

                      /**
                      * Adds custom field for Product
                      * @return [type] [description]
                      */
    function wdm_add_custom_fields()
       {

          global $product;
          ob_start();

          $terms = get_the_terms( $product->get_id(), 'product_cat' );

          // Loop through term objects
            foreach( $terms as $term ) {
              if ( "ballons" === $term->slug ) {
        ?>
          <div class="wdm-custom-fields">
            <label>Color </label>
             <select type="text" name="wdm_name">     
                <option value="blue">Blue</option>
                <option value="red">Rojo</option>
                <option value="green">Green</option>      
            </select>
         </div>
         <div class="clear"></div>
    <br>
    
    <?php 
      //  break; // The term match, we stop the loop.
        }
       }        
      ?>

The select box appears in all products , seems like the above code is not restricting the select box to the specific category, any help would be appreciate it选择框出现在所有产品中,似乎上面的代码没有将选择框限制为特定类别,任何帮助将不胜感激

Use instead the dedicated Wordpress conditional function has_term() as follow:使用专用的 Wordpress 条件函数has_term()如下:

add_action('woocommerce_before_add_to_cart_button', 'before_add_to_cart_button_custom_fields');
function before_add_to_cart_button_custom_fields() {
    global $post, $product;

    // Here define your terms (can be terms Ids, slugs or names)
    $terms = array('ballons');

    if ( has_term( $terms, 'product_cat' ) ) {
    ?>
    <div class="wdm-custom-fields">
        <label><?php _e("Color", "woocommerce"); ?></label>
        <select type="text" name="wdm_name">
            <option value="blue"><?php _e("Blue", "woocommerce"); ?></option>
            <option value="red"><?php _e("Rojo", "woocommerce"); ?></option>
            <option value="green"><?php _e("Green", "woocommerce"); ?></option>
        </select>
    </div>
    <div class="clear"></div>
    <br>
    <?php
    }
}

Code goes in functions.php file of your active child theme (or active theme).代码位于活动子主题(或活动主题)的 functions.php 文件中。 Tested and works.测试和工作。

You should replace wdm_name simply by color everywhere in your code您应该在代码中随处使用color替换wdm_name

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM