在收到的Woocommerce订单上的if语句中使用产品类型(thankyou)

问题描述 投票:1回答:1

我正在开展一个项目,我不得不将Woocommerce产品类型称为“简单”,“可变”,“分组”或“外部”......

我想要实现的目标: 在感谢页面上,其中显示“谢谢。您的订单已收到。”。 如果产品是“简单”而另一个文本是产品变量或分组或外部,我想在那里显示特定文本,所以类似于:

if (product->get_type() == 'simple') {// (for simple product)
      //show a text
}else {// (for variable, grouped and external product) 
      //show another text
}

我已经能够使用这个:

function custome_tank_you_text($order_id) {
    $order = new WC_Order( $order_id );
    $items = $order->get_items();

    foreach ( $items as $item ) {
        $product = wc_get_product( $item['product_id'] );

        $product->get_type();
    }

    if( $product == 'simple'){ ?>
        <p class="woocommerce-notice woocommerce-notice--success woocommerce-thankyou-order-received"><?php echo apply_filters( 'woocommerce_thankyou_order_received_text', __( 'Thank you for topping up your wallet. It has been updated!', 'woocommerce' ), $order ); ?></p>
    <?php
    } else {?>
    <p class="woocommerce-notice woocommerce-notice--success woocommerce-thankyou-order-received"><?php echo apply_filters( 'woocommerce_thankyou_order_received_text', __( 'Thank you. Your order has been received!', 'woocommerce' ), $order ); ?></p>
    <?php
    }
}
add_shortcode('thank-u-msg', 'custome_tank_you_text');

但这只会回应Else的声明。

有什么我做错了吗?

php wordpress woocommerce product orders
1个回答
3
投票

更新:

自从Woocommerce 3以来,你的代码有点过时并且有一些错误...还要记住订单可以有很多项,所以需要打破循环(保留第一项)。

您可以通过这种方式直接使用专用过滤器钩woocommerce_thankyou_order_received_text

add_filter( 'woocommerce_thankyou_order_received_text', 'custom_thankyou_order_received_text', 20, 2 );
function custom_thankyou_order_received_text( $thankyou_text, $order ){
    // Loop through order items
    foreach ( $order->get_items() as $item ) {
        // Get an instance of the WC_Product Object from the WC_Order_Item_Product
        $product = $item->get_product();

        if( $product->is_type('simple') ){
            $thankyou_text = __( 'Thank you for topping up your wallet. It has been updated!', 'woocommerce' );
        } else {
            $thankyou_text = __( 'Thank you. Your order has been received!', 'woocommerce' );
        }
        break; // We stop the loop and keep the first item
    }
    return $thankyou_text;
}

代码位于活动子主题(或活动主题)的function.php文件中。测试和工作。

$order

相关:Get Order items and WC_Order_Item_Product in Woocommerce 3


添加 - 如何获取WC_Product对象(使用is_type()方法)

您无法全局获取产品类型...因为它取决于WC_Product对象

1)从动态产品id变量(当你没有$ product对象时:

$product = wc_get_product( $product_id );

要么

$product = wc_get_product( get_the_id() );

2)购物车项目:

// Loop throught cart items
foreach( WC()->cart->get_cart() as $cart_item ){
    $product = $cart_item['data'];
}

3)订购商品:

// Loop through order items
foreach ( $order->get_items() as $item ) {
    $product = $item->get_product();
}
© www.soinside.com 2019 - 2024. All rights reserved.