【问题标题】:wc_update_order_item not saving correctlywc_update_order_item 未正确保存
【发布时间】:2018-11-21 01:45:25
【问题描述】:

我正在尝试更新 wp_woocommerce_order_items 表中的项目名称并找到函数 wc_update_order_item 来解决问题。

我希望它更改为随机挑选的产品。他们的主要内容是我已经知道我想要更改的order_item_id

这是我的代码:

    $order_item_id = array(1,2,3);
    $num = 3;
    $ctr = 0;

    $products = new WP_Query( array(
       'post_type'      => 'product',
       'post_status'    => 'publish',
       'posts_per_page' => $num,
       'orderby'        => 'rand',
    ));

    if ( $products->have_posts() ): while ( $products->have_posts() ): $products->the_post();

        wc_update_order_item($order_item_id[$ctr], array('order_item_name' => $products->post->post_title));

        $ctr++;

    endwhile; wp_reset_postdata(); endif;

wc_update_order_item() 是应该更新订单商品名称的地方。它确实更新了 order_item_name,但不更新当前的 $products->post->post_title 值。它使用随机产品标题更新。

我如何知道正在保存的标题与循环内的当前 post_title 不同?如果我在循环内echo $products->post->post_title,它应该显示当前产品名称,但更新后的order_item_name 具有不同的值。

【问题讨论】:

    标签: php wordpress woocommerce product orders


    【解决方案1】:

    尝试以下操作,获取与 Order 项目对应的相关产品 ID,将它们从 WP_Query 中排除,避免产品名称相同:

    $order_item_ids = array(1,2,3);
    $num = 3;
    $ctr = 0;
    
    $exluded_ids = array();
    
    // Loop through the Order items Ids
    foreach ( $order_item_ids as $item_id ) {
        // Get the order ID from the order Item ID
        $order_id = wc_get_order_id_by_order_item_id( $item_id );
    
        // Get the WC_Order object instance
        $order = wc_get_order( $order_id );
    
        // Get the WC_Order_Item_Product object instance
        $item = $order->get_item( $item_id );
    
        // Products IDs to be excluded from the WP_Query (array)
        $exluded_ids[] = $item->get_product_id();
    }
    
    $products = new WP_Query( array(
       'post_type'      => 'product',
       'post_status'    => 'publish',
       'posts_per_page' => $num,
       'orderby'        => 'rand',
       'post__not_in'   => $exluded_ids,
    ));
    
    if ( $products->have_posts() ): 
        while ( $products->have_posts() ): $products->the_post();
            wc_update_order_item($order_item_id[$ctr], array('order_item_name' => $products->post->post_title));
            $ctr++;
    
        endwhile; 
        wp_reset_postdata(); 
    endif;
    

    它应该可以工作。


    现在,由于我们不知道您是如何获得 $order_item_id 数组的,因此无法知道实际发生了什么。最好从一开始就解释您要做什么。

    【讨论】:

    • 谢谢。实际上没有生成重复的产品名称。只是$products->post->post_title 的值与循环中的值不同。我删除了查询中的'orderby' => 'rand',,问题就消失了。我确实需要产品是随机的,所以每次都不是同一个产品。
    • @badboy 但是您的实际代码不可测试,因为它不允许重现您的问题。您应该尝试在您的问题中给出上下文,因为我们真的没有抓住这个故事。 $order_item_id = array(1,2,3); 没有帮助,$ctr = 0; 设置为空。
    猜你喜欢
    • 2013-10-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-29
    • 1970-01-01
    • 2019-03-14
    • 2012-01-29
    相关资源
    最近更新 更多