简体   繁体   中英

How to set multiple selected values for Select field type programmatically?

I have a field my-field

Type of my-field is Select

Field property Allow multiple is enabled.

Available values of the field are

  • value-1
  • value-2
  • value-3

If I update field manually and then the call function

get_field( 'my-field', 'option' );

I've got

[
    0 =>
        [
            'value' => 'value-1',
            'label' => 'value-1',
        ],
    1 =>
        [
            'value' => 'value-2',
            'label' => 'value-2',
        ],
];

Attempt 1

If I try to update field - I call function update_field this way

$update_result_multiple = update_field(
    'my-field',
    [
        0 =>
            [
                'value' => 'value-1',
                'label' => 'value-1',
            ],
        1 =>
            [
                'value' => 'value-2',
                'label' => 'value-2',
            ],
        2 =>
            [
                'value' => 'value-2',
                'label' => 'value-3',
            ],
    ],
    'option'
);

I've got update_result_multiple is false and all values become unselected

Attempt 2

If I try this way - selected value has been updated successfully.

$update_result = update_field(
    'my-field',
    [
        'value' => 'value-1',
        'label' => 'value-1',
    ],
    'option'
);

The problem is

I can't update Select field by setting selected multiple values.

Only manually I could set selected multiple values. But can't with update_field function

The question is

How to set selected multiple values for Select field type with update_field function?

Or also you can use by this method too.

// Save a checkbox or select value.
$field_name = "my-field";
    
$value = array("value-1", "value-2", "value-3");
    
update_field( $field_name , $value, 'option' )

for more information please check the update_field documentation

I've discovered the way to solve the problem.

I've called get_fields with third argument formatted-value = false .

This gives me the clue to understand right format.

Then I've called update_field this way

$update_result_multiple = update_field(
    'my-field',
    ['value-1', 'value-2', 'value-3'],
    'option'
);

And field successfully updated.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM