Ask any question about WordPress here... and get an instant response.
Post this Question & Answer:
How can I create a custom post type with unique meta fields in WordPress?
Asked on Mar 03, 2026
Answer
Creating a custom post type with unique meta fields in WordPress involves registering the post type and adding custom fields to it. This can be done using code in your theme's `functions.php` file or via a custom plugin.
<!-- BEGIN COPY / PASTE -->
// Register Custom Post Type
function create_custom_post_type() {
$args = array(
'label' => 'Books',
'public' => true,
'supports' => array('title', 'editor', 'custom-fields'),
);
register_post_type('book', $args);
}
add_action('init', 'create_custom_post_type');
// Add Meta Box for Custom Fields
function add_custom_meta_box() {
add_meta_box(
'book_details',
'Book Details',
'display_book_meta_box',
'book',
'normal',
'high'
);
}
add_action('add_meta_boxes', 'add_custom_meta_box');
function display_book_meta_box($post) {
$author = get_post_meta($post->ID, 'book_author', true);
echo 'Author: <input type="text" name="book_author" value="' . esc_attr($author) . '" />';
}
// Save Meta Box Data
function save_book_meta_box_data($post_id) {
if (array_key_exists('book_author', $_POST)) {
update_post_meta($post_id, 'book_author', sanitize_text_field($_POST['book_author']));
}
}
add_action('save_post', 'save_book_meta_box_data');
<!-- END COPY / PASTE -->Additional Comment:
- Custom post types allow you to create content types beyond the default posts and pages.
- Meta boxes are used to add custom fields to your custom post type, enabling you to store additional data.
- Ensure you have the capability to edit theme files or create a plugin to add this functionality.
- Always back up your site before making changes to the code.
Recommended Links:
