-- 创造无限可能

wordpress开发:购物车商品中添加自定义的属性

2022-06-18 18:07:16
542 人浏览 8 人点赞
有用,点赞支持一下

场景:客户在购买商品时,有时候需要用户添加一些自定义信息,比如:备注、颜色等。

实现:我们以添加一个备注属性作为案例

  1. 添加产品属性
    产品->属性->添加属性(属性slug:remark)
  2. 在产品详情页面添加输入框

    function add_name_remark() {
         echo ' <input type="text" name="remark" value="" />';
    }
    add_action( 'woocommerce_before_add_to_cart_button', 'add_name_remark' );
    
  3. 保存自定义属性

    add_action( 'woocommerce_add_cart_item_data', 'save_in_cart_my_custom_product_field', 10, 2 );
    function save_in_cart_my_custom_product_field( $cart_item_data, $product_id ) {
     if( isset( $_POST['remark] ) ) {
     $cart_item_data[ 'remark' ] = $_POST['remark'];
     // When add to cart action make an unique line item
     $cart_item_data['unique_key'] = md5( microtime().rand() );
     WC()->session->set( 'custom_data', $_POST['remark'] );
     }
     return $cart_item_data;
    }
    
  4. 在购物车和结账页面显示自定义属性

    // 显示自定义数据
    add_filter( 'woocommerce_get_item_data', 'render_custom_field_meta_on_cart_and_checkout', 10, 2 );
    function render_custom_field_meta_on_cart_and_checkout( $cart_data, $cart_item ) {
     $custom_items = array();
     if( !empty( $cart_data ) )
         $custom_items = $cart_data;
     if(isset($cart_item['remark']) && $custom_field_value = $cart_item['remark'] )
     $custom_items[] = array(
         'name' => __( 'Reamrk', 'woocommerce' ),
         'value' => $custom_field_value,
         'display' => $custom_field_value,
     );
     return $custom_items;
    }
    
  5. 保存自定义属性到购物车

    add_action( 'woocommerce_add_order_item_meta', 'tshirt_order_meta_handler', 10, 3 );
    function tshirt_order_meta_handler( $item_id, $cart_item, $cart_item_key ) {
     $custom_field_value = $cart_item['remark'];
     if( ! empty($custom_field_value) )
         wc_update_order_item_meta( $item_id, 'remark', $custom_field_value );
    }