Metabox Tutorial – Add Form Inputs To Metabox

Share this Article

Metabox purpose is to provide information to user or allow the user to do some operation. In this tutorial we will see how to add few form elements to custom metabox.

So far we learnt to show a static information message to user by custom metabox.

custom-metabox-at-post-page-wordpress
custom-metabox-at-post-page-wordpress

To create custom metabox, we need these –

  • Action hook add_meta_boxes
  • add_meta_box function
  • Callback function of metabox

We will take form elements as – Text input & Textarea. You can definitely add more input elements in same pattern.

Example

/**
 * Register meta box(es).
 */
function owt_register_post_meta_box()
{
    add_meta_box('meta-box-id', __('My Meta Box', 'textdomain'), 'owt_my_display_callback', 'post');
}
add_action('add_meta_boxes', 'owt_register_post_meta_box');

/*
 * Custom metabox callback function 
 */
function owt_my_display_callback($post)
{
?>
    <p>
        <input type="text" placeholder="Author name" name="author_name" class="widefat" size="20">
    </p>
    <p>
        <textarea class="widefat" name="author_desc" placeholder="Add your description"></textarea>
    </p>
<?php
}

Above code adds a metabox inside Create Post / Edit Post page. You can add this code into your custom plugin code or add inside activated theme functions.php file.

Explanation

  • Above code will add metabox into post page.
  • Metabox will have two inputs.
  • Input elements have a class widefat, default class given by wordpress to use for design.
  • Must specify the name attributes for input elements because with this name key it will save data into wp_postmeta table.

In the next tutorial we will see how to save input values to database table.

Learn Web Development Courses @ $4 only.
Web Development Courses @ $4