簡體   English   中英

付款后將產品添加到訂單中(WooCommerce/Wordpress)

[英]Add products to order after payment (WooCommerce/Wordpress)

我正在創建一個“構建你自己的”頁面。 從選項中選擇 4 個產品后,1 個主要產品被添加到購物籃中,其中 4 個所選產品被添加為該主要產品下的元數據。

您可以在主產品下方看到 4 個選定的產品 (ID)。

在此處輸入圖片說明

為這個項目付款后,我需要將每個選定的產品添加到訂單中,以便它們在后端的訂單內。 我不得不這樣做,因為我需要所選產品的庫存下降,最終進入我們使用的庫存管理系統(veeqo)

任何幫助表示贊賞。 下面的代碼允許我獲得 woocommerce_thankyou 的一些元數據,但我不確定它是否會起作用......

add_action('woocommerce_thankyou', 'BuildYourOwn', 10, 1);
function BuildYourOwn( $order_id ) {
    if ( !$order_id ){
        return;
    }
    $firstTime = get_post_meta( $order_id, '_thankyou_action_done', true );
    // Allow code execution only once 
    if( !$firstTime ) {

        // Get an instance of the WC_Order object
        $order = wc_get_order( $order_id );

        $exItems = '';
        // Loop through order items
        foreach ( $order->get_items() as $item_id => $item ) {
            //print_r($item);
            // Get the product object
            $product = $item->get_product();

            // Get the product sku
            $product_sku = $product->get_sku();

            // Get the product name
            $product_id = $product->get_name();

            $extras = $item->get_formatted_meta_data('_', true);
            
            $exItems.=$product_sku;

            if(!empty($extras)){
                $exItems.=$product_sku.' -';
                
                foreach($extras as $extra){
                    $exItems.= ' ['.$extra->key.' : '. preg_replace("/[^A-Za-z0-9?@,.&%!\s]/","",$extra->value).'] ';
                }
                
            }
            $exItems.="\n";

        }
        
        var_dump($exItems);

也許我的問題措辭錯誤 - 但我想通了:

我使用下面的代碼來獲取 meta_data,然后我循環遍歷並獲取單個項目 id 並以這種方式將其添加到籃子中。

// Get the product meta data
        $extras = $item->get_formatted_meta_data('_', true);
        
        
        if ($product_id == 60023){

            if(!empty($extras)){
                
                $args = array(
                    'subtotal'     => 0,
                    'total'        => 0,
                  );
                
                foreach($extras as $extra){
                    $mini_name = $extra->value;
                    
                    $mini = get_page_by_title( $mini_name, OBJECT, 'product' );
                    $mini_id = $mini->ID; 
                    
                    $order->add_product( wc_get_product($mini_id), 1, $args); // Add Minis
                }
            }
        }

唯一的小問題是 woocommerce_thankyou 鈎子不會觸發,如果 paypal 用戶在付款后沒有返回網站。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM