Skip to content

How to add custom meta box to wordpress admin interface

When building a plugin sometimes is handy to add custom information and/or forms into a wordpress post admin screen, the wordpress api allows you to program this behavior using the add_meta_box function.

As an example, i will take you through the exercise of adding a functionality of adding a custom metabox for a recipe post type, that will allow the user to define the cooking time for the recipe.

1. The expected result

2. Adding a custom metabox on the sidebar

Metaboxes are added by WP into the screen using the WordPress event trigger ‘add_meta_boxes’, therefore let’s add our metabox design into the events queue.

add_action( ‘add_meta_boxes’, ‘add_recipe_time_metabox’ );

The second parameter is the name of our function that will design the metabox (add_recipe_time_metabox).

function add_recipe_time_metabox( $post ){
add_meta_box( ‘recipe_metabox’, __( ‘Recipe Time’, ‘recipe_time_plugin’ ), ‘recipe_time_metabox_markup’, ‘post’, ‘side’, ‘high’, null );
}

The definition of the add_meta_box function can be found on the WordPress add_meta_box function page.

add_meta_box( string $id, string $title, callable $callback, string|array|WP_Screen $screen = null, string $context = ‘advanced’, string $priority = ‘default’, array $callback_args = null )

On this example my meta_box will have the following values:

  • $id=’recipe_metabox’
  • $title=’Recipe Time’
  • $callback=’recipe_time_metabox_markup’ (This is the markup for the meta_box_content)
  • $screen=’post’ (Showing the meta_box on the post screen)
  • $content=’side’ (Sidebar placement)
  • $priority=’high’ (show on top)

3. Defining the meta_box content

As you noticed we just passed the function ‘recipe_time_metabox_markup’ as callback for the meta_box, let’s fill the contact using it.

function recipe_time_metabox_markup() {
echo ‘<p class=”post-attributes-label-wrapper”><label class=”post-attributes-label”>__( ‘Preparation time’ )</label></p>’;
echo ‘<input type=”text” name=”recipe_time_in_seconds” value=”0″ size=”4″/> ‘.__( ‘minutes’);
}

Of course, this would not be useful if he data is not saved, i will make a follow up post on handling data saving for the meta_box area on WordPress, using the save_post trigger soon.

Edit: Just created a sequence for this post that explains “How to save custom meta box fields on WordPress“!

Published inCodingphpwordpress

Be First to Comment

Leave a Reply

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