How to add a form-field to your Custom Post Type (CPT) #
After you created your custom post type you can simply modify the form
-Array of your CPT-configuration in Configuration/CPT/book.php
.
This way you can create custom forms and fields to add additional data to your CPT in the WordPress backend when editing the post. Following the WordPress tradition, this data is stored in the table postmeta
of your database.
Let's add two input-fields for the ISBN-number of the book and a link to the homepage of the author.
File: Configuration/CPT/book.php
#
<?php
$cptConfig = [
'labels' => [
'name' => 'Books',
'singular_name' => 'Book',
],
'description' => 'List of books from the example extension.',
'public' => true,
'has_archive' => true,
'menu_icon' => 'dashicons-book',
'menu_position' => 20,
'supports' => ['title', 'editor', 'custom-fields', 'thumbnail'],
'rewrite' => ['slug' => 'example'],
];
$bookInfoForm = [
'ctrl' => [
'title' => 'Additional Infos',
'position' => 'right,bottom',
],
'columns' => [
'isbn' => [
'label' => 'ISBN-number',
'config' => [
'type' => 'input',
'size' => 30,
'max' => 255,
],
],
'www' => [
'label' => 'Author website',
'config' => [
'type' => 'input',
'placeholder' => 'https://...',
],
],
],
];
return [
'config' => $cptConfig,
'forms' => [$bookInfoForm]
];
Done.
When editing your CPT, you now will see a new form on the right bottom column with two input fields.
nnhelpers
takes care of all the complicated things like rendering the form-fields, adding a nonce for security and writing / updating the data in the postmeta
-database table.
Convention over Configuration #
The form-data will be saved as postmeta
-data using the convention _{pluginname}_{fieldname}
.
In the example above we are in a plugin called example
and have defined two fields with the names isbn
and www
. These will be saved in the table postmeta
with the meta_key _example_isbn
and _example_www
.