Vấn đề gặp phải khi sử dụng select <option> array trong Wordpress
12th Jul 2021I am trying to create a drop down list box in woocommerce but have it populated with data from the database.
I have the majority of the code working but the portion to populate the list box is killing me. This is what I have so far.
// Display Extra Fields on General Tab Section
add_action( 'woocommerce_product_options_general_product_data', 'woo_add_custom_general_fields' ); function woo_add_custom_general_fields() { global $post; // Set HERE the product attribute taxonomy $taxonomy = 'pa_breed'; // Get the selected value <== <== (updated) $value = get_post_meta( $post->ID, '_select', true ); if( empty( $value ) ) $value = ''; $dog_breeds = get_terms( $taxonomy, array( 'hide_empty' => false, 'order' => 'ASC', 'fields' => 'names' ) ); $options[''] = __( 'Select a value', 'woocommerce'); // default value foreach ($dog_breeds as $key => $term) $options[$term] = $term; // <=== <=== <=== Here the correct array echo '<div class="options_group">'; woocommerce_wp_select( array( 'id' => '_select', 'label' => __( 'My Select Field', 'woocommerce' ), 'options' => $options, //this is where I am having trouble 'value' => $value, ) ); echo '</div>'; } // Save Fields add_action( 'woocommerce_process_product_meta', 'woo_add_custom_general_fields_save' ); function woo_add_custom_general_fields_save( $post_id ){ // Select $woocommerce_select = $_POST['_select']; if( !empty( $woocommerce_select ) ) update_post_meta( $post_id, '_select', esc_attr( $woocommerce_select ) ); else { update_post_meta( $post_id, '_select', '' ); } }
Kết quả
Add new comment