Olasunkanmi
Olasunkanmi

Reputation: 333

Woocommerce Dynamic Checkout Form fields

I am currently working on a wordpress website. I customized my woo commerce checkout page to include an additional form field with this code in my function.php child theme. It works well.

add_action('woocommerce_after_order_notes', 'my_custom_checkout_fields');

function my_custom_checkout_fields($checkout){

echo '<div id="my_custom_checkout_fields"><h2>' .__('New Field').'</h2>';

woocommerce_form_field('my_field_name', array(
    'type' =>'text',
    'class'=>array('my-field-class form-row-wide'),
    'label'=>__('Fill this field'),
    'placeholder'=>__('Enter Something'),
    ), $checkout->get_value('my_field_name'));

echo '</div>';

}

I want to have this form field repeat itself in accordance to the quantity of a product ordered. Lets say I ordered a product 3 times, I want the form field to appear 3 times at the checkout. Help Anyone?

Upvotes: 1

Views: 1740

Answers (1)

LoicTheAztec
LoicTheAztec

Reputation: 254383

Updated - This can be easily with 2 loops inside your hooked function:

  • The first iterate through each cart item
  • The second one for each unit related to the quantity

So for example if you have a 2 cart items: first has a quantity of 3 and second a quantity of 2, you will get 5 custom checkout text fields.

add_action('woocommerce_after_order_notes', 'my_custom_checkout_fields', 20, 1 );
function my_custom_checkout_fields( $checkout ){
     $index = 0;

    echo '<div id="my_custom_checkout_fields"><h2>' .__('New Field').'</h2>';

    // First Loop go through cart items
    foreach( WC()->cart->get_cart() as $cart_item ) {
        // 2nd Loop go through each unit related to item quantity
        for( $i = 1; $i <= $cart_item['quantity']; $i++ ) {
            $index++;

            woocommerce_form_field('my_field_name_'.$index, array(
                'type' =>'text',
                'class'=>array('my-field-class form-row-wide'),
                'label'=>__('Fill this field') . ' ' . $index,
                'placeholder'=>__('Enter Something'),
            ), $checkout->get_value('my_field_name_'.$index));

        }
    }

    echo '</div>';

}

Code goes in function.php file of your active child theme (or active theme). Tested and works

Upvotes: 1

Related Questions