Search code examples
phpwordpresswoocommercewidgetshortcode

Display of custom field value in Woocommerce widget area…


I am having difficulty displaying the result of addition off all numerical values in custom fields for a woocommerce basket. So basically there is a custom field which is stored the m3 of the item.

I am wanting to display the value of all custom fields combined - i.e the total shipping volume in a widget area on the sidebar. The code below was kindly generated for me and shows the total shipping volume of the checkout pages great

add_action( 'woocommerce_cart_totals_before_shipping', 'display_cart_volume_total', 20 );
add_action( 'woocommerce_review_order_before_shipping', 'display_cart_volume_total', 20 );
function display_cart_volume_total() {
    $total_volume = 0;

    // Loop through cart items and calculate total volume
    foreach( WC()->cart->get_cart() as $cart_item ){
        $product_volume = (float) get_post_meta( $cart_item['product_id'], '_item_volume', true );
        $total_volume  += $product_volume * $cart_item['quantity'];
    }

    if( $total_volume > 0 ){

        // The Output
        echo ' <tr class="cart-total-volume">
            <th>' . __( "Total Shipping Volume", "woocommerce" ) . '</th>
            <td data-title="total-volume">' . number_format($total_volume, 2) . ' m3</td>
        </tr>';
    }
}

How do I show the total on a page somewhere - say in a widget area?

I have tried the following:

<?php 
echo ' <tr class="cart-total-volume">
            <th>' . __( "Total Shipping Volume", "woocommerce" ) . '</th>
            <td data-title="total-volume">' . number_format($total_volume, 2) . ' m3</td>
        </tr>';

?>

Solution

  • You can create a custom shortcode from your function this way:

    add_shortcode( 'shipping_volume', 'display_total_shipping_volume' );
    function display_total_shipping_volume( $atts ) {
        ob_start(); // Start buffering output
    
        echo '<table>';
    
        display_cart_volume_total();
    
        echo '</table>';
    
        // Render output from buffer
        return ob_get_clean();
    }
    

    And you can use [shipping_volume] in the default Wordpress "Text" widget…

    enter image description here

    or as a php snippet:

    <?php echo '<table>'; display_cart_volume_total(); echo '</table>'; ?>