A meta box is a draggable box shown on a post edit page, usually on sidebar. Category box, tags box are some of the in-built meta boxes. A meta box can be used to select or enter any information additional to the post. Let’s say you have a custom post type book. You can create a custom meta box your CPT book which will take input as author’s name, publisher, price, year, etc and save this information in wp_postmeta table.
Creating a meta box requires three steps:
- Creating the box itself,
- Define content of meta box,
- How to handle input data from box.
Defining Meta Box and the content
add_action('add_meta_boxes', 'book_meta_box');
function book_meta_box(){
add_meta_box(
'book_info_box',
'Book Information',
'book_box_content,
'book',
'side'
);
}
function book_box_content($post){
echo '<label for="price"> Price </label>';
echo '<input type="text" id="price" name="price" placeholder="Enter price" />';
}
Handling/saving input data
add_action('save_post', 'save_book_info');
function save_book_info($post_id, $post) {
/* Verify the nonce before proceeding. */
/* Get the post type object. */
$post_type = get_post_type_object( $post->post_type );
/* Check if the current user has permission to edit the post. */
if ( !current_user_can( $post_type->cap->edit_post, $post_id))
return $post_id;
$book_price = $_POST['price'];
update_post_meta( $post_id, 'book_price', $book_price );
}
Following are the frequently used functions for post meta:
- add_post_meta(): Adds post metadata.
- update_post_meta(): Updates post metadata.
- delete_post_meta(): Deletes post metadata.
- get_post_meta(): Retrieves post metadata.