WooCommerce デジタル(ダウンロード)商品は住所入力なしにするfunctions.php 設定手順

WordPressにECサイト機能を追加できるWooCommerce。発送する商品と発送が不要なデジタル商品の両方の場合、発送が不要な商品だと、決済フォームに住所は不要になる。

バーチャル商品の住所欄をなしに

WooCommerceの場合、発送が不要なデジタル商品、つまり、ダウンロード商品は、「バーチャル」オプションをONにすると、設定できる。

バーチャル をONに設定した商品のみの決済では、住所入力欄をなしに。

発送あり商品のときは、住所入力欄を必須に。

これを実現するには、functions.phpに以下のコードを追記するとOK。

注意事項
functions.phpを理解している方向け記事です。カスタマイズ方法を失敗すると、ブログが真っ白になる等トラブルが起きても自己解決できる方向け記事です。

functions.phpに追記するコード

/* デジタル商品 住所 カット */

add_filter( 'woocommerce_checkout_fields' , 'bbloomer_simplify_checkout_virtual' );
 
function bbloomer_simplify_checkout_virtual( $fields ) {
    
   $only_virtual = true;
    
   foreach( WC()->cart->get_cart() as $cart_item_key => $cart_item ) {
      // Check if there are non-virtual products
      if ( ! $cart_item['data']->is_virtual() ) $only_virtual = false;   
   }
     
    if( $only_virtual ) {
       unset($fields['billing']['billing_company']);
       unset($fields['billing']['billing_address_1']);
       unset($fields['billing']['billing_address_2']);
       unset($fields['billing']['billing_city']);
       unset($fields['billing']['billing_postcode']);
       unset($fields['billing']['billing_country']);
       unset($fields['billing']['billing_state']);
       unset($fields['billing']['billing_phone']);
       add_filter( 'woocommerce_enable_order_notes_field', '__return_false' );
     }
     
     return $fields;
}

/* end デジタル商品 住所 カット */

これで、バーチャル商品のときは、

名前とメールアドレスのみの、入力欄に切り替わる。

弊社のオンラインショップの場合、

発送ありの商品は、こちら↓

バーチャルの発送なし商品は、こちら↓

参考記事はこちら