By default, the data stored using custom meta boxes is stored in postmeta table. You may want to create your own table to store data related to your custom post type. They are called custom meta tables and they are created by extending Metadata API.
Following are the steps to create custom meta tables:
- Create custom table to store metadata.
- Make WordPress aware of meta table.
- Optionally define wrapper class that makes it easier to interact with your metadata layer.
Create table
dbDelta() is a function provided by WordPress to create and modify tables.
$response = dbDelta(
CREATE TABLE `wp_bookmeta` (
`meta_id` bigint(20) NOT NULL AUTO_INCREMENT,
`book_id` bigint(20) NOT NULL DEFAULT '0',
`meta_key` varchar(255) DEFAULT NULL,
`meta_value` longtext,
PRIMARY KEY (`meta_id`),
KEY `book_id` (`book_id`),
KEY `meta_key` (`meta_key`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
);
Where,
- meta_id is the id of meta which is auto incremented.
- book_id is the id of book post type to which metadata belongs to.
- meta_key is the name of the metadata e.g. price.
- meta_value is value of that key e.g. 20.
Registering table with WordPress
function pw_register_metadata_table() {
global $wpdb;
$wpdb->bookmeta = $wpdb->prefix . 'wp_bookmeta';
}
add_action( 'plugins_loaded', 'pw_register_metadata_table' );
You will have to pass ‘book’ as object type when interacting with meta table as ‘book’ is followed by ‘meta’. If you register it as ‘examplemeta’, you have to pass ‘example’ as object type.
Interacting with metadata
$added = add_metadata('book', $book_id, 'price', 20);
$value = get_metadata('book', $book_id, 'price', single=true);
$deleted = delete_metadata('book', $book_id, 'price');
update_metadata has same structure as add_metadata.