Join Patrick Rauland for an in-depth discussion in this video Validate settings, part of WordPress Ecommerce: WooCommerce Plugins.
- [Instructor] Now that we've added a 'Settings' page, it's time to update and save these settings. When we're adding settings, we created a function that didn't really do anything. It just called another function. I don't typically write code like that but I did do it in this case, because I knew what was coming next. We need to pass these exact same fields right here into another function and in the exact same format. This 'get settings' function here is actually going to serve two purposes.
It's used to display the fields and it's also used to update them. This is called DRY programming. DRY means Do not Repeat Yourself. The idea is that if you ever have to repeat yourself, you're going to make a mistake. If you're going to declare fields in one function and update them in another, you're probably going to, at one point or another, update one and not the other. That's why I created this little function so I only have to update it in one place. In a previous video, we discovered a dynamic hook for displaying settings.
There's another one for updating settings. Let's copy and paste this line but instead of this action, we're going to change it to 'woocommerce_update_options' and then 'opening_hours'. Then we're going to change 'add_settings' here to 'update_settings'. Now we need to write this method, 'update settings', so I'll copy this and paste it right there.
I'll add a little function describing what it does. 'Woocommerce_admin_fields' will display them on the settings page. We want to use something slightly different. We're going to use 'woocommerce_update_options' with the same parameter. Now let's save this file and go back to our settings and make sure that everything's working. I'll refresh this and then I'll click 'Save Changes'. Now it looks like it's saving, whether it's empty or checked.
Easy-peasy once you know what you're doing. As an aside, there's a lot of these in woocommerce. You'll probably start writing out something the wrong way and you may have to re-write parts of it once you see how all the code works together. That's just a part of learning a new code base so if you find yourself re-writing things, don't worry, that's to be expected.
- Creating a WooCommerce plugin
- Finding hooks within WooCommerce
- Creating settings pages
- Analyzing WooCommerce settings
- Configuring settings
- Customizing the edit product page
- Using hooks on the product page
- Customizing the WooCommerce checkout
- Adding custom order statuses
Skill Level Intermediate
Q: This course was updated on 08/07/2018. What changed?
A: The following topics were updated: adding a meta box, saving product fields, customizing product titles, and adding data to product page tabs.