访问 Woocommerce 上的自定义全局变量 谢谢

Access a custom global variable on Woocommerce thankyou

我正在尝试将全局变量设置为标志。我想在 thankyou.php 模板中使用它来在订购的商品缺货时显示自定义消息。没用。

我的代码在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;    
} 

thankyou.php 模板中我添加了这个:

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

相反,您可以在活动主题的 functions.php 文件 中使用以下内容(这将在下订单时将其保存为自定义订单元数据,然后再保存数据):

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 );
    }
}

然后在您的 thankyou.php 模板文件中,您将使用以下 (因为 WC_Order 对象存在):

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