
Saving Settings for a Custom WordPress Block in the Block Editor
There’s one last bit for us to cover and that’s saving the settings options. If we recall from the last article, we’re technically able to “save” our selections in the block settings UI, but those aren’t actually stored anywhere. If we make a few selections, save them, then return to the post, the settings are completely reset.
Let’s close the loop and save those settings so they persist the next time we edit a post that contains our custom block!
We’re working with an API that provides us with soccer football team ranking and we’re using it to fetch for displaying rankings based on country, league, and season. We can create new attributes for each of those like this:
Next, we need to set the attributes from LeagueSettings.js
. Whenever a ComboboxControl
is updated in our settings UI, we need to set the attributes using the setAttributes()
method. This was more straightfoward when we were only working with one data endpoint. But now that we have multiple inputs, it’s a little more involved.
This is how I am going to organize it. I am going to create a new object in LeagueSettings.js
that follows the structure of the settings attributes and their values.
I am also going to change the initial state variables from null
to the respective settings variables.
In each of the handle______Change()
, I am going to create a setLocalAttributes()
that has an argument that clones and overwrites the previous localSettings
object with the new country, league, and season values. This is done using the help of the spread operator.
We can define the setLocalAttributes()
like this:
Finally, we can use the setAttributes()
as we do normally to set the final object. You can confirm if the above attributes are changing by updating the selections in the UI.
Another way to confirm is to do a console.log() in DevTools to find the attributes.
Look closer at that screenshot. The values are stored in attributes.settings
. We are able to see it happen live because React re-renders every time we make a change in the settings, thanks to the useState()
hook.
It isn’t very useful to store the setting values in the control options themselves since each one is dependent on the other setting value (e.g. rankings by league depends on which season is selected). But it is very useful in situations where the settings values are static and where settings are independent of each other.
While I’m here, I am going to do a conditional check for the values before displaying them inside the Tip
component:
Here’s how that winds up working in the block editor:
API data is more powerful when live data can be shown without having to manually update them each and every time. We will look into that in the next installment of this series.
If you need help creating a digital marketing strategy for your business, don’t hesitate to contact one of Digidude’s consultants.
Post a Comment
You must be logged in to post a comment.