将自定义产品元数据传递到Woocommerce 4中的订单

时间:2020-03-26 10:30:09

标签: wordpress woocommerce

我正在尝试将自定义产品元数据传递给订单。我可以将自定义产品元数据保存在管理员中,但是结帐时很难将值保存到订单元数据中。我正在使用Woo4。有人可以帮忙吗?谢谢,谢谢。

add_action( 'woocommerce_product_options_general_product_data', 'product_meta_create_email_field' );
function product_meta_create_email_field() {
    $args = array(
        'id'            => 'email_estabelecimento',
        'label'         => __( 'Email do Estabelecimento', 'cfwc' ),
        'class'         => 'cfwc-custom-field',
        'desc_tip'      => true,
        'description'   => __( 'Insere aqui o email do estabelecimento.', 'ctwc' ),
    );
    woocommerce_wp_text_input( $args );
}

add_action( 'woocommerce_process_product_meta', 'product_meta_save_email_field' );
function product_meta_save_email_field( $post_id ){
    if( isset( $_POST['email_estabelecimento'] ) )
        update_post_meta( $post_id, 'email_estabelecimento', esc_attr( $_POST['email_estabelecimento'] ) );
}

add_action('woocommerce_checkout_create_order_line_item', 'save_email_as_order_item_meta', 20, 4);
function save_email_as_order_item_meta($item, $cart_item_key, $values, $order) {
    if ( $estabelecimento = $values['data']->get_meta('email_estabelecimento') ) {
        $item->update_meta_data( 'email_estabelecimento', $estabelecimento );
    }
}

1 个答案:

答案 0 :(得分:1)

您已经很近了,这里和那里做了一些小的调整

// Adding a custom field in the back-end
function product_meta_create_email_field() {
    $args = array(
        'id'            => 'email_estabelecimento',
        'label'         => __( 'Email do Estabelecimento', 'cfwc' ),
        'class'         => 'cfwc-custom-field',
        'desc_tip'      => true,
        'description'   => __( 'Insere aqui o email do estabelecimento.', 'ctwc' ),
    );
    woocommerce_wp_text_input( $args );
}
add_action( 'woocommerce_product_options_general_product_data', 'product_meta_create_email_field', 10, 0 );

// Saving the custom field value
function product_meta_save_email_field( $post_id ) {
    // Get product
    $product = wc_get_product( $post_id );

    // $_POST
    $email_estabelecimento = isset( $_POST['email_estabelecimento'] ) ? $_POST['email_estabelecimento'] : '';

    // Update meta data
    $product->update_meta_data( 'email_estabelecimento', esc_attr( $email_estabelecimento ) );

    // Save
    $product->save();

}
add_action( 'woocommerce_process_product_meta', 'product_meta_save_email_field', 10, 1 );

// Displaying custom fields in the WooCommerce order and email confirmations
function save_email_as_order_item_meta($item, $cart_item_key, $values, $order) {
    $email_estabelecimento = $values['data']->get_meta('email_estabelecimento');

    if ( isset( $email_estabelecimento ) ) {
        $item->update_meta_data( 'email_estabelecimento', $email_estabelecimento );
    }
}
add_action('woocommerce_checkout_create_order_line_item', 'save_email_as_order_item_meta', 20, 4);