Search code examples
phpwordpresswoocommerceordersshipping-method

Display all available shipping methods and costs on WooCommerce Order pages


Previous / Related Question: Display ALL available shipping methods for each specific order on admin edit order pages in Woocommerce

Currently in my WooCommerce based site, I am wanting to display the available shipping methods and prices on the order edit page.

It does not display the data as I want. For example, the output of my code so far results in:

Method 1
Method 2
Method 3

Price 1
Price 2
Price 3

When alternatively, I would like for it to display like this:

Method 1 - $Price 1
Method 2 - $Price 2
Method 3 - $Price 3

I understand why it is displaying this way, but I was curious how I could iterate the loops at the same time and format them, rather than one after the other.

This is my code so far:

add_action( 'woocommerce_admin_order_data_after_shipping_address', 'action_woocommerce_admin_order_data_after_shipping_address', 10, 1 );
function action_woocommerce_admin_order_data_after_shipping_address( $order ){
    // Get meta
    $rate_labels = $order->get_meta( '_available_shipping_methods' );
    $rate_costs = $order->get_meta( '_available_shipping_method_cost' );
    
    $methods = array ( $rate_labels, $rate_costs );
    
    // True
    if ( $rate_labels ) {
        // Loop
        echo '<p><strong>Shipping Methods: </strong>';
        foreach( $rate_labels as $rate_label ) {
            // Output
            echo '<p>' . $rate_label . '</p>';
        }
        foreach( $rate_costs as $rate_cost ) {
            // Output
            echo '<p> $' . $rate_cost . '</p>';
        }
    }
}

Solution

  • In case anyone happens to have the same question as I did, here is how I did it:

    function action_woocommerce_admin_order_data_after_shipping_address( $order ) {
        // Get meta
        $rate_labels = $order->get_meta( '_available_shipping_methods' );
        $rate_costs = $order->get_meta( '_available_shipping_method_cost' );
        
        $methods = array ( $rate_labels, $rate_costs );
        
        // True
        if ( $rate_labels ) {
            // Loop
            echo '<p><strong>Shipping Methods: </strong>';
            foreach(array_combine($rate_labels, $rate_costs) as $rate_label => $rate_cost) {
                 echo '<p>' . $rate_label . ' - $' . $rate_cost . '</p>';
            }
        }
        
    }