Home › Forums › Add-ons › Repeater Field › 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 );
}
}
}
You must be logged in to reply to this topic.
Welcome to the Advanced Custom Fields community forum.
Browse through ideas, snippets of code, questions and answers between fellow ACF users
Helping others is a great way to earn karma, gain badges and help ACF development!
We use cookies to offer you a better browsing experience, analyze site traffic and personalize content. Read about how we use cookies and how you can control them in our Privacy Policy. If you continue to use this site, you consent to our use of cookies.