🧱 Module 7: Custom Post Types & Meta Boxes
Custom Post Types (CPTs) let you store structured content like “Books,” “Events,” or “Products.” Meta Boxes let you add custom fields for each item — like “Author,” “Price,” or “Date.”
Step 1 – Register a Custom Post Type
(📋 You can copy or edit directly below)
function mfp_register_books_cpt() {
$labels = array(
'name' => 'Books',
'singular_name' => 'Book',
'add_new_item' => 'Add New Book',
'edit_item' => 'Edit Book',
'menu_name' => 'Books'
);
$args = array(
'labels' => $labels,
'public' => true,
'show_in_menu' => true,
'menu_icon' => 'dashicons-book-alt',
'supports' => array('title', 'editor', 'thumbnail'),
'has_archive' => true,
);
register_post_type('book', $args);
}
add_action('init', 'mfp_register_books_cpt');
Step 2 – Add a Meta Box to the CPT Editor
function mfp_add_book_meta_box() {
add_meta_box(
'mfp_book_details',
'Book Details',
'mfp_render_book_meta_box',
'book',
'normal',
'default'
);
}
add_action('add_meta_boxes', 'mfp_add_book_meta_box');
function mfp_render_book_meta_box($post) {
$author = get_post_meta($post->ID, '_mfp_book_author', true);
wp_nonce_field('mfp_save_book_meta', 'mfp_book_meta_nonce');
echo '<label>Author Name:</label><br>';
echo '<input type="text" name="mfp_book_author" value="' . esc_attr($author) . '" style="width:100%;" />';
}
Step 3 – Save the Meta Box Data
function mfp_save_book_meta($post_id) {
if (!isset($_POST['mfp_book_meta_nonce']) ||
!wp_verify_nonce($_POST['mfp_book_meta_nonce'], 'mfp_save_book_meta')) {
return;
}
if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) return;
if (isset($_POST['mfp_book_author'])) {
update_post_meta($post_id, '_mfp_book_author', sanitize_text_field($_POST['mfp_book_author']));
}
}
add_action('save_post_book', 'mfp_save_book_meta');
✅ Now your WordPress site has a new “Books” post type with an editable “Author Name” field. Try adding a few Books from the dashboard → Books → Add New!
No comments:
Post a Comment