Pass custom product meta data to the order in Woocommerce 3

后端 未结 1 770
一整个雨季
一整个雨季 2021-01-22 08:21

In Woocommerce, I\'m attempting to add a piece of custom meta to my products and I would like to pass it through to orders.

We have a substantial amount of products and

1条回答
  •  南笙
    南笙 (楼主)
    2021-01-22 08:42

    I have revisited a bit your code. The following will save your product custom field "Cost centre" as hidden order item meta data, visible only in Admin Order edit pages on each item:

    // Admin products: Display custom Field
    add_action( 'woocommerce_product_options_general_product_data', 'product_options_general_product_data_add_field' );
    function product_options_general_product_data_add_field() {
        global $post;
    
        echo '
    '; woocommerce_wp_select( array( 'id' => '_cost_centre', 'label' => __( 'Cost Centre', 'woocommerce' ), 'options' => array( 'MFEG' => __( 'MFEG', 'woocommerce' ), // Default displayed option value 'YDIT' => __( 'YDIT', 'woocommerce' ), ) ) ); echo '
    '; } // Admin products: Save custom Field add_action( 'woocommerce_process_product_meta', 'product_options_general_product_data_save_field' ); function product_options_general_product_data_save_field( $post_id ){ if( isset( $_POST['_cost_centre'] ) ) update_post_meta( $post_id, '_cost_centre', esc_attr( $_POST['_cost_centre'] ) ); } // Order items: Save product "Cost centre" as hidden order item meta data add_action('woocommerce_checkout_create_order_line_item', 'save_file_type_as_order_item_meta', 20, 4); function save_file_type_as_order_item_meta($item, $cart_item_key, $values, $order) { if ( $cost_centre = $values['data']->get_meta('_cost_centre') ) { $item->update_meta_data( '_cost_centre', $cost_centre ); // Save as order item (visble on admin only) } }

    Code goes in functions.php file of your active child theme (or active theme). Tested and works.

    Export: (In StackOverFlow, the rule is one question for one answer).

    The WordPress/Woocommerce basic order export don't allow to export order items

    You will need to use a third party plugin and depending on the chosen plugin, you will have to add your order item custom field _cost_centre for your export based on the plugin possibilities.

    0 讨论(0)
提交回复
热议问题