Ask any question about WordPress here... and get an instant response.
How can I create a custom post type with specific metadata in WordPress?
Asked on Dec 21, 2025
Answer
Creating a custom post type in WordPress allows you to organize and display different types of content beyond the default posts and pages. You can also add specific metadata to enhance the custom post type's functionality.
function my_custom_post_type() {
$labels = array(
'name' => 'Books',
'singular_name' => 'Book',
'menu_name' => 'Books',
'name_admin_bar' => 'Book',
'add_new' => 'Add New',
'add_new_item' => 'Add New Book',
'new_item' => 'New Book',
'edit_item' => 'Edit Book',
'view_item' => 'View Book',
'all_items' => 'All Books',
'search_items' => 'Search Books',
'parent_item_colon' => 'Parent Books:',
'not_found' => 'No books found.',
'not_found_in_trash' => 'No books found in Trash.'
);
$args = array(
'labels' => $labels,
'public' => true,
'publicly_queryable' => true,
'show_ui' => true,
'show_in_menu' => true,
'query_var' => true,
'rewrite' => array('slug' => 'book'),
'capability_type' => 'post',
'has_archive' => true,
'hierarchical' => false,
'menu_position' => null,
'supports' => array('title', 'editor', 'author', 'thumbnail', 'excerpt', 'comments'),
'register_meta_box_cb' => 'add_books_metaboxes'
);
register_post_type('book', $args);
}
add_action('init', 'my_custom_post_type');
function add_books_metaboxes() {
add_meta_box('wpt_books_author', 'Book Author', 'wpt_books_author', 'book', 'side', 'default');
}
function wpt_books_author() {
global $post;
$author = get_post_meta($post->ID, 'book_author', true);
echo '';
}
function save_books_meta($post_id, $post) {
if ($post->post_type == 'book') {
update_post_meta($post_id, 'book_author', sanitize_text_field($_POST['book_author']));
}
}
add_action('save_post', 'save_books_meta', 1, 2);
Recommended Links:
← Back to All Questions
