php - WooCommerce form field select in cart that lists custom post types ← (PHP)
I have created a custom post type good_cause. I can pull the custom post type's title and populate a drop down on the cart.
What I'm trying to accomplish is for the post's titles to be the options in the woocommerce_form_field instead of the static value.
<?php
add_action('woocommerce_before_order_notes', 'wps_add_select_checkout_field');
function wps_add_select_checkout_field( $checkout ) {
echo '<h2>'.__('Select a Good Cause').'</h2>';
$args = array(
'post_type' => 'good_cause',
'posts_per_page' => -1,
);
$query = new WP_Query($args);
if ($query->have_posts() ) :
echo '<select>';
while ( $query->have_posts() ) : $query->the_post();
echo '<option value="' . get_the_ID() . '">' . get_the_title() . '</option>';
endwhile;
echo '</select>';
wp_reset_postdata();
endif;
woocommerce_form_field( 'daypart', array(
'type' => 'select',
'class' => array( 'wps-drop' ),
'label' => __( 'Delivery options' ),
'options' => array(
'blank' => __( 'Select a day part', 'wps' ),
'morning' => __( 'In the morning', 'wps' ),
'afternoon' => __( 'In the afternoon', 'wps' ),
'evening' => __( 'In the evening', 'wps' )
)
),
$checkout->get_value( 'daypart' ));
}
Answer
Solution:
Instead of printing these (echo) you can add the values to an $options
array, then use this array as woocommerce_form_field( 'options' );
function wps_add_select_checkout_field( $checkout ) {
echo '<h2>'.__('Select a Good Cause').'</h2>';
$args = array(
'post_type' => 'good_cause',
'posts_per_page' => -1,
);
$query = new WP_Query($args);
// Set variable (array)
$options = array();
if ( $query->have_posts() ) :
while ( $query->have_posts() ) : $query->the_post();
// Add to $options array
$options[get_the_ID()] = get_the_title();
endwhile;
wp_reset_postdata();
endif;
woocommerce_form_field( 'daypart', array(
'type' => 'select',
'class' => array( 'wps-drop' ),
'label' => __( 'Delivery options' ),
'options' => $options
), $checkout->get_value( 'daypart' ));
}
add_action('woocommerce_before_order_notes', 'wps_add_select_checkout_field', 10, 1 );