Creating loop within functions.php

I’m using Woocommerce on my website, on the checkout page I’ve got a custom select checkout field with radio buttons. I’m using this working snippet within my functions.php:

/**
* Add the field to the checkout
**/
add_action( 'woocommerce_after_order_notes', 'custom_select_field' );
function hear_about_us_field( $checkout ) {
    echo '<div id="custom-field"><h3>'
        . __( '2. Pick an option' )
        . '</h3>';
    woocommerce_form_field_radio( 
        'custom_field', 
        array(
            'type' => 'select',
            'class' => array(
                'custom-select-field'
             ),
            'label' => __( '' ),
            'placeholder' => __( '' ),
            'required' => true,
            'options' => array(
                'Option 1' => 'Option 1',
                'Option 2' => 'Option 2',
                'Option 3' => 'Option 3'
            )
        ),
        $checkout->get_value( 'custom_field' )
    );
    echo '</div>';
}

As you can see there is 3 select options I’ve added manually. What I want is to add options dynamically based on custom post types.

When displaying Custom post types I usually run a loop like this:

<?php $loop = new WP_Query( array( 'post_type' => 'organisationer') ); ?>
<?php while ( $loop->have_posts() ) : $loop->the_post(); ?>
<?php the_title(); ?>
<?php endwhile; wp_reset_query(); ?>

How can I implement this loop within the checkout function? S

instead of “Options 1”, “Option 2” I for example want the title of a CPT.

1 Answer
1

Just loop over WP_Query::$posts to get the titles:

$option_posts = new WP_Query( [ 'post_type' => 'organisationer' ] );
$options      = [];
foreach ( $option_posts->posts as $post ) {

    $key = "option_{$post->ID}";
    $options[ $key ] = apply_filters( 'the_title', $post->post_title );
}

woocommerce_form_field_radio( 
    'custom_field', 
    array(
        /* … */
        'options' => $options
    ),
    $checkout->get_value( 'custom_field' )
);

I’m not sure what exactly woocommerce_form_field_radio expects as parameter. Maybe you have to flip the key and value in the associative array $option. But this is basically how to get a list of post titles from a query object. You may also consider to remove the the_title filter, depending on your needs.

Leave a Comment