There are times in WordPress when you need a custom field, but may not want to go through setting up a full custom meta box. Sometimes all you need is a simple checkbox that appears in the publish box. In this how-to, I’ll show you how to add a custom meta checkbox field to the existing post publish box.
This code can be placed in your theme’s functions.php file, however, I recommend adding it in a custom plugin. As a rule of thumb, if you will miss the functionality if you changed the theme, put it in a plugin – Â leave the theme for front end display functionality only… but that’s a bigger discussion.
Adding the field
First we will need to hook into post_submitbox_misc_actions
to add the custom field, and save_post
to save the field.
Then we need to create the functions being called within those, first we will create the custom field using the createCustomField
function we specified above.
This function gets the post ID from the post we’re currently in. We then want to check that the field only gets added to post types we want it to show on, in this example the custom field will only get added to WordPress posts. We then get the existing custom meta, set our nonce, and output the field.
Once the field is created, we need a way to save the field data. This is where the saveCustomField
function is needed.
This function checks that it is not an autosave, our nonce is set, and the user has the correct permissions to edit the post. If any of those fail, we return and don’t update the custom field. When we update/ save the post and our set conditions pass, we check the field is set and update the custom field post meta. If the post meta isn’t set, we remove it.
It’s that simple! Click here to view the gist with these examples in it.
– Emily Fox
Interested in working with us? See our open engineering roles here.