I am creating a widget, it needs to store about 10 IDs. Right now I’m using following field method to store each of the ID in a separate field. It stores data of each field in a separately in the wordpress. Is it possible to store the data of all fields in just one row in wordpress for examlpe using an array?
<input
class="widefat"
id="<?php echo $this->get_field_id('item1_id'); ?>"
name="<?php echo $this->get_field_name('item1_id'); ?>"
value="<?php echo $instance['item1_id']; ?>"
/>
<input
class="widefat"
id="<?php echo $this->get_field_id('item2_id'); ?>"
name="<?php echo $this->get_field_name('item2_id'); ?>"
value="<?php echo $instance['item2_id']; ?>"
/>
You have to collect multiple fields under the same name like this â¦
⦠and adjust your widget logic to this.
Here is a very simple demo widget:
Backend
Frontend
The above answer is good if you need the fields to be numbered. In my case, I didn’t. I have a widget with options that allow the user to select any number of categories to be used within the widget.
Here’s my widget
form
. — Three important things herearray()
if the widget’s value is not set<label>
name
attribute, notice that I attach a[]
at the end. This tells PHP that I’m submitting an array of values for this key<label><input type="checkbox" ...></label>
. — Each of our checkboxes will not have a uniqueid
attribute, so the<label>
for
attribute will not work. We could generate unique IDs, but that’s a hassle. If you just wrap the label around the input, the label get associated properly without the hassle of connecting thefor
+id
Now the code
And here’s my update function
I’m interested in saving the Category IDs in an array, which are numbers, so I use
array_map
withintval
to ensure that all submitted datum are valid integers. Additionally, I usearray_filter
to remove any invalid submissions.It’s particularly challenging to describe this WordPress stuff. If you have any questions, I’ll be happy to elaborate.