custom meta box in wordpress

A custom meta box in WordPress is basically an extra content box that you can add to the post, page, or custom post type editing screen inside the WordPress admin.

How it Works

  1. Register the meta box using add_meta_box().
  2. Create the fields (input, select, textarea, etc.).
  3. Save the field data using save_post.
  4. Retrieve and display the data on the frontend.

// 1. Add custom meta box
function my_custom_meta_box() {
add_meta_box(
‘movie_details’, // ID
‘Movie Details’, // Title
‘my_custom_meta_box_callback’, // Callback
‘movies’, // Post type
‘normal’, // Context
‘high’ // Priority
);
}
add_action(‘add_meta_boxes’, ‘my_custom_meta_box’);

// 2. Meta box HTML
function my_custom_meta_box_callback($post) {
$director = get_post_meta($post->ID, ‘_director’, true);
?>
Director:
<?php
}

// 3. Save meta box data
function save_my_custom_meta_box($post_id) {
if (array_key_exists(‘director’, $_POST)) {
update_post_meta(
$post_id,
‘_director’,
sanitize_text_field($_POST[‘director’])
);
}
}
add_action(‘save_post’, ‘save_my_custom_meta_box’);

After this, whenever you edit a Movie post, you’ll see a box called Movie Details with a “Director” field. The value is saved in the database as post meta.

Share on Facebook Share on Twitter