woocommerce-将自定义产品字段添加到订单项元

时间:2019-06-17 10:13:13

标签: php wordpress woocommerce hook-woocommerce

我正在使用以下代码在产品中添加额外的字段并将其保存在订单明细中。它适用于简单产品,但在可变产品项中,自定义字段不能保存在订单元数据中。

// Display Fields
add_action( 'woocommerce_product_options_inventory_product_data', 'woo_add_guarantee_fields' );

function woo_add_guarantee_fields() {

  global $woocommerce, $post;

  echo '<div class="options_group">';

// Select
woocommerce_wp_select( 
array( 
    'id'      => 'guarantee_select', 
    'label'   => __( 'guarantee', 'woocommerce' ), 
    'options' => array(
        '' => __( '', 'woocommerce' ),
        '1'   => __( '1', 'woocommerce' ),

        )
    )
);  
  echo '</div>';

}

// Save Fields
add_action( 'woocommerce_process_product_meta', 'woo_add_guarantee_fields_save' );

function woo_add_guarantee_fields_save( $post_id ){ 

    $woocommerce_select = $_POST['guarantee_select'];
    if( !empty( $woocommerce_select ) )
        update_post_meta( $post_id, 'guarantee_select', esc_attr( $woocommerce_select ) );

}

// Order items: Save product "guarantee_field" as hidden order item meta data
add_action('woocommerce_checkout_create_order_line_item', 'woo_add_guarantee_fields_order', 50, 4);
function woo_add_guarantee_fields_order($item, $cart_item_key, $values, $order) {
    if ( $guarantee_field = $values['data']->get_meta('guarantee_select') ) {
        $item->update_meta_data( 'guarantee', $guarantee_field ); 
    }
}

0 个答案:

没有答案