Our code has a lot of redundancies in it. Moving to a single meta box key within
$_POST allows us the ability to refactor our code and build a loop to remove the redundancies. It also makes it easier to merge the incoming data with defaults.
Why would we want to merge the data with defaults? Think about that checkbox. When it’s not checked, that key and value will not be sent back to the web server and will not be in
$_POST. To ensure that we are working with all of our meta box’s metadata (custom fields), we merge the incoming data with defaults. It makes our code more predictable as we ensure that we have everything we expect before we go into the loop.
After merging, then we can loop through each of the meta keys and values, check if it needs to be deleted, run the validation and sanitizing, and then update.
Your functions are bloated. Put them on a diet. Think "skinny" and "as few lines as possible."
Total Lab Runtime: 02:21:18
- 1 Lab Introductionfree 07:20
- 2 What is a Meta Box?free 07:28
- 3 Add a New Meta Boxpro 11:46
- 4 Meta Box HTMLpro 18:39
- 5 Save Process & $_POSTfree 12:33
- 6 Bail Out if Not Our Meta Boxpro 05:03
- 7 Nonce Security Checkpro 10:16
- 8 On Save - Update or Delete Custom Field?pro 12:03
- 9 Validate & Sanitize BEFORE Updating Databasefree 14:41
- 10 Add Another Custom Fieldpro 08:49
- 11 Making Save Easier with $_POST Keypro 05:32
- 12 Better Saving Strategy for Multiple Custom Fieldspro 14:47
- 13 Changing Where Meta Box Appearspro 06:02
- 14 Passing Arguments to Renderpro 02:18
- 15 Wrap & Making it Reusablepro 04:01