Add multiple products programmatically in WooCommerce from ACF repeater

Question

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:

$product_ids = [];
    $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);
                $product_ids[] = $product_id;
            }
        }
    }

    $new_product_price = 0;
    $productextra    = wc_get_product( $product_id );
    $productextra->set_price( $new_product_price );
    $item_id    = $order->add_product( $productextra, 1 );
0
user3344734 8 months 2020-12-01T02:10:26-05:00 0 Answers 14 views 0

Leave an answer

Browse
Browse