Support

Account

Home Forums Add-ons Repeater Field Add multiple products programmatically in WooCommerce from ACF repeater

Helping

Add multiple products programmatically in WooCommerce from ACF repeater

  • I am adding products programatically in WooCommerce and I am trying to add multiple free products to an order. The Free products are selected in the theme settings via an Advanced Custom Fields repeater. This repeater has no limit, so can be several products.

    I have managed to to get one product to show (the latest created in the repeater) with a price of 0. How Do I create so if I have more then one product selected the order gets updated with all of these as separate line items? I assume a foreach loop somehow?

    Current relevant code:

    
        $current_date = strtotime(date('Y-m-d H:i:s'));
        $categories   = get_field('free_product_category', 'option');
    
        if(have_rows('theme_free_products', 'options')){
            while(have_rows('theme_free_products', 'options')){
                the_row();
                $start_date = get_sub_field('start_date');
                $end_date = get_sub_field('end_date');
                if(strtotime($start_date) <= $current_date && strtotime($end_date) > $current_date){
                    $product_id = get_sub_field('product', false);
                }
            }
        }
    
        $new_product_price = 0;
        $productextra    = wc_get_product( $product_id );
        $productextra->set_price( $new_product_price );
        $item_id    = $order->add_product( $productextra, 1 );
  • Solved by placing everything inside the loop.

    
    $current_date = strtotime(date('Y-m-d H:i:s'));
        if(have_rows('theme_free_products', 'options')){
            while(have_rows('theme_free_products', 'options')){
                the_row();
                $start_date = get_sub_field('start_date');
                $end_date = get_sub_field('end_date');
                if(strtotime($start_date) <= $current_date && strtotime($end_date) > $current_date){
                    $product_id = get_sub_field('product', false);
    				$productextra    = wc_get_product( $product_id );
    				$new_product_price = 0;
    				$productextra->set_price( $new_product_price );   
    				$item_id    = $order->add_product( $productextra );             
                    
                }
            }
        }
    
    
Viewing 2 posts - 1 through 2 (of 2 total)

You must be logged in to reply to this topic.