WordPress is an immensely flexible content management system that allows developers to create custom post types, taxonomies, and metadata. One of the most powerful ways to extend WordPress is through the use of meta boxes. A meta box is simply a custom user interface element that allows you to add additional information (metadata) to a post, page, or custom post type.
The add_meta_box
function is a core WordPress function that allows developers to register a new meta box on a particular post type. This function takes four parameters:
$id
: A unique identifier for the meta box.$title
: The title of the meta box (displayed to the user).$callback
: The name of the function that will render the contents of the meta box.$post_type
: The post type(s) to which this meta box should be added.
Once you have registered a meta box using the add_meta_box
function, you can then use the get_post_meta
and update_post_meta
functions to read and write metadata associated with that post.
Here’s an example of how to use the add_meta_box
function to create a meta box that allows users to add a custom subtitle to a post:
function my_custom_meta_box() {
add_meta_box(
'my-custom-meta-box',
'Custom Subtitle',
'my_custom_meta_box_callback',
'post'
);
}
function my_custom_meta_box_callback( $post ) {
$subtitle = get_post_meta( $post->ID, '_custom_subtitle', true );
?>
<label for="custom-subtitle">Enter a custom subtitle:</label>
<input type="text" id="custom-subtitle" name="custom-subtitle" value="<?php echo esc_attr( $subtitle ); ?>">
<?php
}
add_action( 'add_meta_boxes', 'my_custom_meta_box' );
function save_custom_subtitle( $post_id ) {
if ( isset( $_POST['custom-subtitle'] ) ) {
update_post_meta( $post_id, '_custom_subtitle', sanitize_text_field( $_POST['custom-subtitle'] ) );
}
}
add_action( 'save_post', 'save_custom_subtitle' );
This example registers a new meta box called "Custom Subtitle" on the "post" post type. When a user edits a post, they will see a new input field called "Enter a custom subtitle". Whatever the user enters into this field will be saved as metadata associated with the post. The save_custom_subtitle
function ensures that this metadata is saved when the user clicks "Update".