在Woocommerce中,我试图向我的产品添加一个自定义元,我希望将其传递给订单。
我们有大量的产品,它们要对不同的成本中心负责,因此我需要在产品管理员内部选择一个框,以便我们选择将价值传递给订单的成本中心,客户无需查看该成本中心,但是管理员必须在订单中以及每个月的订单出口中都可以查看以进行会计处理。
这是我到目前为止所拥有的,它将在产品编辑页面(admin)中显示选择框:
// Display Fields
add_action( 'woocommerce_product_options_general_product_data', 'woo_add_custom_general_fields' );
function woo_add_custom_general_fields() {
global $woocommerce, $post;
echo '<div class="options_group">';
woocommerce_wp_select(
array(
'id' => '_select',
'label' => __( 'Cost Centre', 'woocommerce' ),
'options' => array(
'one' => __( 'MFEG', 'woocommerce' ),
'two' => __( 'YDIT', 'woocommerce' ),
)
)
);
echo '</div>';
}
// Save Fields
add_action( 'woocommerce_process_product_meta', 'woo_add_custom_general_fields_save' );
function woo_add_custom_general_fields_save( $post_id ){
// Select
$woocommerce_select = $_POST['_select'];
if( !empty( $woocommerce_select ) )
update_post_meta( $post_id, '_select', esc_attr( $woocommerce_select ) );
}
但是它没有将值传递给订单。
如何将此自定义字段值传递给订单?
我再次回顾了您的代码。以下内容会将您的产品自定义字段“成本中心”保存为隐藏的订单商品元数据,仅在每个商品的“管理订单”编辑页面中可见:
// 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 '<div class="options_group">';
woocommerce_wp_select( array(
'id' => '_cost_centre',
'label' => __( 'Cost Centre', 'woocommerce' ),
'options' => array(
'MFEG' => __( 'MFEG', 'woocommerce' ), // Default displayed option value
'YDIT' => __( 'YDIT', 'woocommerce' ),
)
) );
echo '</div>';
}
// 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)
}
}
代码进入您的活动子主题(或活动主题)的functions.php文件中。经过测试和工作。
出口: (在StackOverflow上,规则是一个问题的一个答案)。
WordPress / Woocommerce基本订单导出不允许导出订单商品
您将需要使用第三方插件,并且根据所选择的插件,您将必须
_cost_centre
根据插件的可能性为导出添加订单项自定义字段。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句