Add custom Metaboxes to wordpress admin post interface

Post Meta Box :

WordPress allow us to add custom meta boxes to posts, pages and custom post types via the admin interface. Creating custom meta boxes is extremely simple, at least it is once you’ve created your first one using any tool/plugin made by WordPress core code.

In this tutorial, I will show you everything you need to know about meta boxes :

  • Creating meta boxes.
  • Displaying Fields in a Custom Meta Box
  • Saving custom metadata

Using metabox we can add extra information to posts or pages apart from default information which is set by WordPress. Editor, Format, Categories, Custom Fields, Tags, Featured Image on a post, page or custom post page admin interface are default meta boxes. They are created by the WordPress core.

Post Meta Data :

Post metadata are values of forms fields which is embedded in metaboxes. WordPress allow us to store this data as Key – Value pair. Form field is stored as Meta key and Meta value is stored as value.

Post Metadata saved in wp_postmeta table in database.

meta_id : A unique ID for this specific metadata.
post_id : The post ID this metadata is attached to.
meta_key : A key used to identify the data (you’ll work with this often).
meta_value : The value of the metadata.

We can use following functions to operate this data.

add_post_meta() : Adds post metadata.
update_post_meta() : Updates post metadata.
delete_post_meta() : Deletes post metadata.
get_post_meta() : Retrieves post metadata.

Creating meta boxes :

add_meta_boxes this hook is used for creating custom meta boxes. This hook will register and display metabox to post or page.

PHP
add_action("add_meta_boxes", "add_custom_meta_box");

function add_custom_meta_box() {
    add_meta_box("custom-meta-box", "Custom Meta Box", "custom_meta_box_callback", "post", "side", "high", null);
}

Displaying Fields in a Custom Meta Box :

we have added some fields for demonstration.

PHP
function custom_meta_box_callback($object) {
    ?>
    <div>
        <label for="extra-info" style="margin-bottom: 5px;float: left;"><strong>Extra Information</strong></label>
        <textarea name="extra-info" rows="4" style="width:100%;"><?php echo get_post_meta($object->ID, "extra-info", true); ?></textarea>
    </div>
    <?php
}

Saving Custom Meta Data :

PHP
add_action( "save_post", "save_custom_meta_box" );

function save_custom_meta_box($post_id) {
    $meta_box_extra_info = "";

    if (isset($_POST["extra-info"])) {
        $meta_box_extra_info = $_POST["extra-info"];
    }
    update_post_meta($post_id, "extra-info", $meta_box_extra_info);

}

Related Posts

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.