如何将 ACF 字段添加到 WooCommerce 管理员订单列表上的自定义列

How to add ACF field to custom column on WooCommerce admin orders list

A​​CF 是为 post WooCommerce 产品类型设置的。但是,我正在尝试向管理仪表板中的 WooCommerce 订单列表添加自定义列并添加产品 ACF 字段。

我在 order_status 之后添加了要显示的列,但我在显示 ACF 字段时遇到问题。

// ADD NEW COLUMN
add_filter( 'manage_edit-shop_order_columns', 'custom_shop_order_column', 20 );
function custom_shop_order_column($columns)
{
    $reordered_columns = array();
    foreach( $columns as $key => $column){
        $reordered_columns[$key] = $column;
        if( $key ==  'order_status' ){
            $reordered_columns['my-column'] = __( 'Location','theme_domain');
        }
    }
    return $reordered_columns;
}

这里,将ACF添加到新列中。

// ADD ACF FIELD TO COLUMN
add_action( 'manage_shop_order_posts_custom_column' , 'custom_orders_list_column_content', 20, 2 );
function custom_orders_list_column_content( $column, $post_id )
{
     if ( 'Location' == $column_name ){
    $product_id = method_exists( $product, 'get_id' ) ? $product->get_id() : $product->id;
    echo get_field( 'location', $product_id );
        }
    return true;
}

还在学习中,不知道该怎么做,有什么建议吗?

一个订单一般由多个产品组成,因此不能直接使用$product_id,必须循环遍历订单项。

所以你得到:

/**
 * Add columns
 */
function filter_manage_edit_shop_order_columns( $columns ) {
    $reordered_columns = array();
    
    foreach ( $columns as $key => $column ) {
        $reordered_columns[$key] = $column;
        
        if ( $key ==  'order_status' ) {
            $reordered_columns['my-column'] = __( 'Location','theme_domain' );
        }
    }
    
    return $reordered_columns;
}
add_filter( 'manage_edit-shop_order_columns', 'filter_manage_edit_shop_order_columns', 10, 1 );

/**
 * Populate columns
 */
function filter_manage_shop_order_posts_custom_column( $column, $post_id ) {
    // Compare
    if ( $column == 'my-column' ) {
        // Get order
        $order = wc_get_order( $post_id );

        // Is a WC_Order
        if ( is_a( $order, 'WC_Order' ) ) {
            // Get items
            $items = $order->get_items();
            
            // Loop through
            foreach ( $items as $key => $item ) {
                // Product ID
                $product_id = $item->get_variation_id() > 0 ? $item->get_variation_id() : $item->get_product_id();
                
                // Get field
                $address = get_field( 'location', $product_id );
                
                // Output
                echo ($address) ? '<div>Address: ' . $address . '</div>' : '<div>Address: No address found!</div>';
            }
        }
    }
}
add_filter( 'manage_shop_order_posts_custom_column', 'filter_manage_shop_order_posts_custom_column', 10, 2 );