To register meta boxes, copy and paste the code below into
functions.php file of your theme or your plugin:
The Meta Box plugin uses
rwmb_meta_boxes filter to register meta boxes. This is a custom filter which takes an array of defined meta boxes as the argument. The callback function must return an array of meta boxes.
Using filter prevents PHP errors if you accidentally forget to install or activate the Meta Box plugin. In that case, the code simply doesn’t run and doesn’t affect the rest of your website.
In the beginning of the code, we defined a prefix for fields:
$prefix = 'rw_';
It will be added before all of our custom field IDs. Using a prefix can prevent us from conflict with other scripts that also use custom fields.
- The prefix is optional. If you don’t want to use it, set it to an empty string or remove it (if you remove it, don’t forget to update
- Use underscore (
_) at the beginning to make the custom fields hidden, e.g. they won’t show in the default WordPress Custom Fields meta box.
- It’s a good practice to have an underscore (
_) as last sign.
Each meta box has the following attributes:
||Meta box ID. Optional. If it’s absent, it will be generated from
||Meta box title. Required.|
||Custom post types which the meta box is for. There can be an array of multiple custom post types or a string for the single post type. Must be in lowercase (like the slug). Optional. Default:
||Part of the page where the meta box is displayed (
||Priority within the context where the box is displayed (
||Hide the meta box by default (
||Auto save the custom fields’ values (like post content and title)? Optional. Default:
||Array of fields. Each field is declared as an array with its parameters. To understand fields’ parameters, please read this documentation.|
Previously, you could register meta boxes using
admin_init hook and a global variable as below:
However, this method has some disadvantages:
- You have to remember the plugin class name (
RW_Meta_Box) to the check if it’s loaded or not which might be changed in the future.
- If there is another code that uses the same global variable to register meta boxes, be careful that the global variable can be overwritten.
- It works in the admin area only
- It’s not compatible with some premium extensions such as Include Exclude, Settings Page, Term Meta.
rwmb_meta_boxes filter as described above, you will have more benefits:
- The code is more elegant and easier to read.
- There is no more global variable, so you never overwrite registered meta boxes by accident. If you want to edit or change existing meta boxes, there’s an instruction for you.
- It’s compatible with all premium extensions.