1

Function is generating select field, what can I do to set 'selected' currently saved value ... if possible? For example, previously I selected 36 and saved "update_option('_nos',$myvalue)"

function woo_add_spin() {
woocommerce_wp_select( 
array( 
    'id'      => '_select_nf',
    'label'   => __( 'Select #spins: ', 'woocommerce' ),
    'selected' => true,
    'options' => array(
        '24'   => __( '24', 'woocommerce' ),
        '36'   => __( '36', 'woocommerce' ),
        '48'   => __( '48', 'woocommerce' )
        )
    )
);

}

so every time function is executed i would like to check current value and set "selected" to the option with the same value or using jQuery check currently set value and just add 'selected' accordingly ?

1

By referencing to the source code, this function supports an argument called value which you can pass one of the keys inside the options array like this:

function woo_add_spin() {
    woocommerce_wp_select([
        'id'       => '_select_nf',
        'label'    => __( 'Select #spins: ', 'woocommerce' ),
        'selected' => true,
        'value'    => '24',
        'options' => [
            '24' => __( '24', 'woocommerce' ),
            '36' => __( '36', 'woocommerce' ),
            '48' => __( '48', 'woocommerce' )
        ]
    ]);
}

By looking inside the source code, WooCommerce also tries to fetch the value of the select field using the id field and the post meta but, you can't take advantage of this built-in feature because you're saving the settings inside the wp_options table.

  • That's perfect Farsad, this works just fine. thank you – Rob D. A. Sep 11 '18 at 9:08

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.