skip to Main Content

I use a plugin to create some custom B2B fields. Now I need these custom made fields to be shown at the checkout page.

function add_custom_b2b_fields_checkout( $fields ){

  $args = array(
    'post_type'           => 'afreg_fields',
    'post_status'         => 'publish',
    'posts_per_page'      => '99',
    'orderby'             => 'name',
  );

  $get_b2b_fields = new WP_Query( $args );

  if ($get_b2b_fields->have_posts()) : while ($get_b2b_fields->have_posts()) : $get_b2b_fields->the_post();
    $fields['billing'][$get_b2b_fields->post_name] = array(
        'type'              => 'text',
        'label'             => get_the_title(),
        'placeholder'       => __(" ", "woocommerce"),
        'class'             => array('b2b-field'),
        'required'          => false,
    );
    endwhile;
    return $fields;
  endif;
}
add_filter( 'woocommerce_checkout_fields', 'add_custom_b2b_fields_checkout' );

The code works nice almost. But it shows only the last field, as if the while run correctly but the return $fields shows only the first custom field instead of all of them.

How can I show all the fields instead of just one? I tried adding a .= at the $fields but that didn’t work.

2

Answers


  1. add_filter( 'woocommerce_checkout_fields', 'add_custom_b2b_fields_checkout' );
    

    change it to

    add_action( 'woocommerce_checkout_fields', 'add_custom_b2b_fields_checkout' );
    

    and add do_action('woocommerce_checkout_fields'); on the page where you want to show

    Login or Signup to reply.
  2. There is a little mistake in your code as $get_b2b_fields->post_name is empty.

    Simply replace:

    $fields['billing'][$get_b2b_fields->post_name] = array(
    

    with:

    $fields['billing'][$get_b2b_fields->post->post_name] = array(
    

    Now it will work.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search