繁体   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