Access a custom global variable on Woocommerce thankyou

Viewed 1062

I'm trying to set a global variable as a flag. I want to use that in the thankyou.php template to show a custom message when the ordered items are not in stock. It doesn't work.

My code in functions.php:

<?php
global $woocommerce;
global $flag_custom_order;
$flag_custom_order=false;
$items = $woocommerce->cart->get_cart();
foreach($items as $item => $values) { 
    $_product =  wc_get_product( $values['data']->get_id()); 
    $stock=$_product->get_stock_quantity();
    if ($stock <= '0') :
        $flag_custom_order=true;
    endif;    
} 

In thankyou.php template i add this:

1 Answers

As cart is emptied once other is placed, the value of $flag_custom_order variable will be always false on Order received (thankyou) page.

Instead you could use the following in your active theme's functions.php file (that will save that as custom order meta data when order is placed, before data is saved):

add_action( 'woocommerce_checkout_create_order', 'action_wc_checkout_create_order',  10, 2  );
function action_wc_checkout_create_order( $order, $data ) {
    $has_backordered_items = false;
    
    if( ! WC()->cart->is_empty() ) {
        foreach(WC()->cart->get_cart() as $cart_item ) { 
            if ( $cart_item['data']->get_stock_quantity() <= 0 ) {
                $has_backordered_items = true;
                break;
            }    
        }
    }
    
    if( $has_backordered_items ) {
        $order->update_meta_data( '_has_backordered_items', $has_backordered_items );
    }
}

Then in your thankyou.php template file you will use the following (as the WC_Order object exist):

<?php 
    if ( $order->get_meta('_has_backordered_items') ) {
        echo '<p>' . __("This order has backordered items.") . '</p>';
    }
?>
Related