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

我正在尝试将全局变量设置为标志。我想在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我添加了这个:


一只斗牛犬
浏览 102回答 1
1回答

猛跑小猪

&nbsp; &nbsp; 由于购物车一旦放入其他商品就会被清空,因此$flag_custom_order变量的值将始终显示false在“收到订单(谢谢)”页面上。functions.php相反,您可以在活动主题的文件中使用以下内容(这将在下订单时、保存数据之前将其保存为自定义订单元数据):add_action( 'woocommerce_checkout_create_order', 'action_wc_checkout_create_order',&nbsp; 10, 2&nbsp; );function action_wc_checkout_create_order( $order, $data ) {&nbsp; &nbsp; $has_backordered_items = false;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp; if( ! WC()->cart->is_empty() ) {&nbsp; &nbsp; &nbsp; &nbsp; foreach(WC()->cart->get_cart() as $cart_item ) {&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if ( $cart_item['data']->get_stock_quantity() <= 0 ) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; $has_backordered_items = true;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; break;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp;&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; &nbsp;&nbsp;&nbsp; &nbsp; if( $has_backordered_items ) {&nbsp; &nbsp; &nbsp; &nbsp; $order->update_meta_data( '_has_backordered_items', $has_backordered_items );&nbsp; &nbsp; }}然后在thankyou.php模板文件中,您将使用以下内容(当WC_Order对象存在时):<?php&nbsp;&nbsp; &nbsp; if ( $order->get_meta('_has_backordered_items') ) {&nbsp; &nbsp; &nbsp; &nbsp; echo '<p>' . __("This order has backordered items.") . '</p>';&nbsp; &nbsp; }?>
打开App,查看更多内容
随时随地看视频慕课网APP