将自定义字段添加到项目元

时间:2019-06-15 23:56:12

标签: woocommerce

我正在使用下面的代码向产品添加额外的字段,并将其按订单明细存储。它适用于简单产品,但在可变产品项中,castom字段不能按顺序保存元数据

// 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 ){ 

    // Select
    $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 个答案:

没有答案