Vấn đề gặp phải khi sử dụng select <option> array trong Wordpress

Written by admin
Posted on Mon, 07/12/2021 - 12:28
9 views

Share Everywhere

Table of contents

I 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ả

I am trying to create a drop down list box in woocommerce but have it populated with data from the database.
Tested in WooCommerce 3+ and works. You will get something similar to this (with your breeds):

 

Add new comment

Restricted HTML

  • Allowed HTML tags: <a href hreflang> <em> <strong> <cite> <blockquote cite> <code> <ul type> <ol start type> <li> <dl> <dt> <dd> <h2 id> <h3 id> <h4 id> <h5 id> <h6 id>
  • Lines and paragraphs break automatically.
  • Web page addresses and email addresses turn into links automatically.
CAPTCHA
This question is for testing whether or not you are a human visitor and to prevent automated spam submissions.
3 + 8 =
Solve this simple math problem and enter the result. E.g. for 1+3, enter 4.
Profile picture for user admin
Câu nói tâm đắc: “Điều tuyệt với nhất trong cuộc sống là làm được những việc mà người khác tin là không thể!”