skip to Main Content

I’m trying to move customer order notes field to another field group, but because of other plugin overrides, I need to override WooCommerce template files too, so I need to move this code:

foreach ( $checkout->get_checkout_fields( 'order' ) as $key => $field ) :
    woocommerce_form_field( $key, $field, $checkout->get_value( $key ) ); 
endforeach;

from: “mytheme/woocommerce/checkout/form-shipping.php
to: “mytheme/woocommerce/checkout/review-order.php“.

Now I’m getting duplicated fields, how to prevent duplicates within foreach loop?

2

Answers


  1. You can maintain an array to keep track of fields you’ve already seen so that they don’t get added again.

    $fields_seen = [];
    foreach ( $checkout->get_checkout_fields( 'order' ) as $key => $field ) :
        if(!in_array($field, $fields_seen)) {
            woocommerce_form_field( $key, $field, $checkout->get_value( $key ) ); 
            $fields_seen[] = $field;
        }
    endforeach;
    

    Reference page for in_array: PHP in_array

    Login or Signup to reply.
  2. You can use array_unique()
    your code will look like this:

    foreach ( array_unique($checkout->get_checkout_fields( 'order' )) as $key => $field ) :
        woocommerce_form_field( $key, $field, $checkout->get_value( $key ) ); 
    endforeach;
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search