0
0
Wordpressframework~30 mins

Custom meta boxes in Wordpress - Mini Project: Build & Apply

Choose your learning style9 modes available
Create Custom Meta Boxes in WordPress
📖 Scenario: You are building a WordPress site for a small business. You want to add extra information fields to the post editor screen so the content creators can add special details easily.
🎯 Goal: Build a custom meta box in the WordPress post editor that allows users to enter a subtitle for each post.
📋 What You'll Learn
Create a function to register a meta box with the ID subtitle_meta_box and title Post Subtitle
Add the meta box to the post post type
Create a callback function to display a text input field with the name post_subtitle
Save the subtitle value when the post is saved
💡 Why This Matters
🌍 Real World
Custom meta boxes let WordPress site owners add extra fields to posts or pages, making content management easier and more tailored to their needs.
💼 Career
Knowing how to create and save custom meta boxes is a common task for WordPress developers customizing themes and plugins.
Progress0 / 4 steps
1
Register the Meta Box
Write a function called add_subtitle_meta_box that uses add_meta_box to add a meta box with ID subtitle_meta_box, title Post Subtitle, callback subtitle_meta_box_callback, and screen post. Then hook this function to add_meta_boxes action.
Wordpress
Need a hint?

Use add_meta_box inside your function and hook it with add_action.

2
Create the Meta Box Callback
Write the function subtitle_meta_box_callback that accepts the $post object. Inside, retrieve the saved meta value with get_post_meta using key post_subtitle. Then output a text input field with name post_subtitle and value set to the retrieved meta value.
Wordpress
Need a hint?

Use get_post_meta to get the saved subtitle and output an input field with that value.

3
Save the Meta Box Data
Write a function called save_subtitle_meta_box_data that accepts $post_id. Inside, check if post_subtitle is set in $_POST. If yes, sanitize it with sanitize_text_field and save it using update_post_meta with key post_subtitle. Hook this function to save_post action.
Wordpress
Need a hint?

Check if post_subtitle is in $_POST, sanitize it, then save with update_post_meta.

4
Add Nonce for Security
In the subtitle_meta_box_callback function, add a nonce field with wp_nonce_field using action save_subtitle_meta_box and name subtitle_meta_box_nonce. Then, in save_subtitle_meta_box_data, verify the nonce from $_POST['subtitle_meta_box_nonce'] using wp_verify_nonce with the same action. If nonce verification fails, return early without saving.
Wordpress
Need a hint?

Use wp_nonce_field in the callback and verify it in the save function with wp_verify_nonce.