Saving all values in “multiple select”

感情迁移 提交于 2019-12-02 20:12:19

问题


im having a metabox in wordpress with a mutliple select form.

<select name="my_meta_box_select" id="my_meta_box_select" multiple="" style="width:300px; height:400px;">
    <option value="red">Red
    </option>
    <option value="blue">Blue
    </option>
</select>

So far so good, the selected value gets saved and I am able to retrieve it, however I wish for both values to be saved.

For example I wish to save both red AND blue and be able to retrieve it from the frontend. Is there any way to achieve this? Are there better forms than a select?

The purpose is for a user to select pages from one select field to another and then save the second select field.

select 1:

red

blue

green

Select 2:

orange

-button-

Now if a user where to select red and blue from select 1 and then press -button- the values will be added to select 2. When I now press update page I wish to save all the values in select 2.

This is how i save from my current select field (but it only saves ONE selected value)

if( isset( $_POST['my_meta_box_select'] ) )
    update_post_meta( $post_id, 'my_meta_box_select', esc_attr( $_POST['my_meta_box_select'] ) );

回答1:


Often overlooked, super simple.

The name attribute needs to allow for multiple selections to be sent over $_POST as an array. For example:

<select name="my_meta_box_select[]" id="my_meta_box_select" multiple="" style="width:300px; height:400px;">
    <option value="red">Red
    </option>
    <option value="blue">Blue
    </option>
</select>

Notice the [] in the name: name="my_meta_box_select[]"

This, alongside the multiple attribute, will allow your $_POST variable to contain all selections as an array. That said, $_POST['my_meta_box_select'] will not just be a simple value, but rather will be an array will all selections.




回答2:


adding [] to the name was correct, however I allso needed to replace the following save line:

update_post_meta( $post_id, 'my_meta_box_select', esc_attr( $_POST['my_meta_box_select'] ) );

with the following:

update_post_meta($post_id, 'my_meta_box_select', array_map( 'strip_tags', $_POST['my_meta_box_select'] ) );

Thanks alot for the assistance Nate!



来源:https://stackoverflow.com/questions/35323688/saving-all-values-in-multiple-select

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!