簡體   English   中英

將自定義字段添加到特定類別的 woocommerce 產品

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

我正在嘗試向我的 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.
        }
       }        
      ?>

選擇框出現在所有產品中,似乎上面的代碼沒有將選擇框限制為特定類別,任何幫助將不勝感激

使用專用的 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
    }
}

代碼位於活動子主題(或活動主題)的 functions.php 文件中。 測試和工作。

您應該在代碼中隨處使用color替換wdm_name

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM