There’s no real need to create meta boxes for use with custom fields because WordPress already includes a custom field meta box.
You can use the native custom fields meta box with unlimited custom fields however creating your own is pretty special once you know how it all works.
So lets take a look at all the code you need to make your own meta box.
Firstly, here’s the finished product which the code generates from your child themes functions file.
You’ll need at least 4 separate functions to generate this box and 5 if you’re not using a theme like Genesis.
Note: Always backup your database before adding PHP code which saves new data.
How The Code Works
- The code firstly registers a meta box with up to 7 parameters hooked into add_meta_boxes. You could also use the add_meta_boxes_post hook.
- It then uses a callback function with wp_create_nonce so data isn’t duplicated in the database and displays the meta box on your Edit Post screens.
- After this it runs through several checks, uses wp_verify_nonce to make sure the nonce is valid and not a duplicate as well as checking the capability of the user using current_user_can before using save_post for saving your content to your database. Also uses update_post_meta if you change the value for your custom field on a specific post.
- The last 2 code snippets basically create a function which you can use with a hook and/or conditional tag to display your custom fields content on the front end if NOT using Genesis.
In this example i’ve added a small editor because it makes it easy to add any type of content and generates HTML.
The name of the custom field is custom_field_box which you can replace with your own.
Was This Tutorial Helpful?