在订单视图列WooCommerce中显示自定义字段值

问题描述 投票:1回答:1

我有这个代码在产品页面上创建一个下拉列表。它保存所选数据并显示在订单上。我需要帮助的是在自定义列中显示值。

这是代码:

add_action( 'woocommerce_product_options_general_product_data', 'costcenter_management_group' );
function costcenter_management_group() {
global $post;
echo '<div class="options_group">';
woocommerce_wp_select( array(
'id'      => '_cost_center',
'label'   => __( 'Cost Center', 'woocommerce' ),
'options' => array(
'One' => __( 'Office One', 'woocommerce' ),
'Two' => __( 'Office Two', 'woocommerce' ),
)));
echo '</div>';
}

// save cost center settings
add_action( 'woocommerce_process_product_meta', 'costcenter_management_group_save' );
function costcenter_management_group_save( $post_id ){
if( isset( $_POST['_cost_center'] ) )
update_post_meta( $post_id, '_cost_center', esc_attr( $_POST['_cost_center'] ) );
}

// display on order
add_action('woocommerce_checkout_create_order_line_item', 'costcenter_management_group_display', 20, 4);
function costcenter_management_group_display($item, $cart_item_key, $values, $order) {
if ( $cost_center = $values['data']->get_meta('_cost_center') ) {
$item->update_meta_data( 'Cost Center', $cost_centre );
}}

// add cost center column on order view (WC admin)
add_filter('manage_edit-shop_order_columns', 'costcenter_management_group_column', 10, 1 );
function costcenter_management_group_column( $columns ) {
$actions_key = isset($columns['wc_actions']) ? 'wc_actions' : 'order_actions';
$order_actions = $columns[$actions_key];
unset($columns[$actions_key]);
$columns['cost_center'] = __("Cost Center", "woocommerce");
$columns[$actions_key] = $order_actions;
return $columns;
}

我知道我可以使用echo,但我不知道我应该使用哪个值?

php wordpress woocommerce metadata orders
1个回答
0
投票

要在自定义列中显示此自定义订单商品元数据,请使用以下内容:

// Display data to custom column in admin orders list
add_action( 'manage_shop_order_posts_custom_column' , 'display_enclosed_invoice_order_column_data' );
function display_enclosed_invoice_order_column_data( $column ) {
    global $the_order, $post;

    if( $column  == 'cost_center' ) {
        $values = []; // Initializing

        // Loop through order items
        foreach ( $the_order->get_items() as $item ) {
            if( $cost_centre = $item->get_meta( 'Cost Center' ) ) {
                $values[] = $cost_centre;
            }
        }
        // Display the value(s)
        if( sizeof( $values ) > 0 ) {
            echo implode( ', ', $values); // Convert the array to a coma separated string
        }
    }
}

代码在您的活动子主题(或活动主题)的function.php文件中。它应该有效。

© www.soinside.com 2019 - 2024. All rights reserved.