WordPress教程

WooCommerce 购物车中有特定产品则显示/移除自定义字段

阿里云

所以我在结帐页的账单部分有一些自定义字段,我只想在购物车中有 ID 为(603)的产品时显示这些自定义字段。这是我使用的当前代码:

  1. function conditional_checkout_fields_products( $fields ) {
  2.         $cart = WC()->cart->get_cart();
  3.  
  4.         foreach ( $cart as $item_key => $values ) {
  5.             $product = $values['data'];
  6.  
  7.             if ( $product->id != 603 ) {
  8.                 unset( $fields['billing']['billing_prev_injuries'] );
  9.                 unset( $fields['billing']['billing_dogs_events'] );
  10.                 unset( $fields['billing']['billing_dogs_age'] );
  11.                 unset( $fields['billing']['billing_dogs_breed'] );
  12.                 unset( $fields['billing']['billing_dogs_name'] );
  13.               }
  14.         }
  15.  
  16.         return $fields;
  17.     }
  18. add_filter( 'WooCommerce_checkout_fields', 'conditional_checkout_fields_products' );
也想出现在这里?联系我们
创客主机

目前上面的代码用于隐藏字段,如果购物车中有一个产品不是 ID 603,但一个问题是当有 603 时,购物车中的另一个产品会取消设置字段,如果 603 不在购物车中,隐藏字段的最佳方法是什么?如果 603 不在购物车中,显示字段的最佳方法是什么?

以下内容将完成此项工作:

  1. add_filter( 'woocommerce_checkout_fields', 'conditional_checkout_fields_products' );
  2. function conditional_checkout_fields_products( $fields ) {
  3.     $is_in_cart = false;
  4.  
  5.     foreach ( WC()->cart->get_cart() as $cart_item ) {
  6.         if ( $cart_item['data']->get_id() == 603 ) {
  7.             $is_in_cart = true;
  8.             break;
  9.         }
  10.     }
  11.  
  12.     if ( ! $is_in_cart ) {
  13.         unset( $fields['billing']['billing_prev_injuries'] );
  14.         unset( $fields['billing']['billing_dogs_events'] );
  15.         unset( $fields['billing']['billing_dogs_age'] );
  16.         unset( $fields['billing']['billing_dogs_breed'] );
  17.         unset( $fields['billing']['billing_dogs_name'] );
  18.     }
  19.  
  20.     return $fields;
  21. }

WooCommerce 购物车中有特定产品则显示/移除自定义字段

已有 189 人购买
查看演示升级 VIP立刻购买

收藏
(0)

发表回复

热销模板

Ashade - 作品展示摄影相册WordPress汉化主题
LensNews

本站承接 WordPress / PbootCMS / DedeCMS 等
系统建站、仿站、开发、定制等业务!