Most of the client ask for additional data to their post beyond the WordPress provided data.
Here’s how to make it.This code snippet will explain how to add additional information with your post. We’ll assume that the blog is all about Stories, the stories contain a title, content, author, and date published.
First, We need to use “add_meta_boxes” hook and “add_meta_box” function to register meta box.
/**
* Register meta box for Author name and Date Published.
*/
function may_custom_register_meta_boxes() {
add_meta_box(
'author-meta-box-id', // (Required) Meta box ID (used in the 'id' attribute for the meta box).
__( 'Author Information: ', 'my_textdomain' ), // (Required) Title of the meta box.
'my_custom_meta_display_callback', // (Required) Function that fills the box with the desired content.
'post' // (Optional) The screen or screens on which to show the box (such as a post type, 'link', or 'comment').
);
}
add_action( 'add_meta_boxes', 'may_custom_register_meta_boxes' );
Second, Display custom fields using the “add_meta_box” callback.
/**
* Meta box display callback.
* Use get_post_meta function to display post metadata
* @URL https://developer.wordpress.org/reference/functions/get_post_meta/
*/
function my_custom_meta_display_callback( $post ) {
?>
<?php
}
Displaying the custom field is not just enough right?
Third, Saving meta box content using the “save_post” hook and “update_post_meta” function.Take note, meta key must be unique
/**
* Save meta box content.
* @param int $post_id Post ID
* @URL https://codex.wordpress.org/Function_Reference/update_post_meta
*/
function my_custom_save_meta_box( $post_id ) {
$author_name = sanitize_text_field( $_POST['author_name'] );
$date_publish = sanitize_text_field( $_POST['date_publish'] );
update_post_meta( $post_id, 'author_name', $author_name );
update_post_meta( $post_id, 'date_publish', $date_publish );
}
add_action( 'save_post', 'my_custom_save_meta_box' );
There you have it, Is it really simple right. Try my other code snippets that will help you make your job much easier.