Do we really need to create custom tables ?
WordPress has it’s own schema covering most of the use cases for our plugins but sometimes, it is not the right solution to use the inbuilt tables only.
Maybe we want to store data very unrelated to what the wordPress already does.
Here is how to create custom table, for that we are going to use `dbDelta()` function that wordpress uses itself when upgrading.
Let’s start by writing the SQL query
global $wpdb;
$table_name = $wpdb->prefix . 'rt-person_meta';
$charset_collate = $wpdb->get_charset_collate();
$sql = "CREATE TABLE `$table_name` (
meta_id bigint(20) NOT NULL AUTO_INCREMENT,
`rt-person_id` bigint(20) NOT NULL DEFAULT '0',
meta_key varchar(255) DEFAULT NULL,
meta_value longtext,
PRIMARY KEY (meta_id),
KEY `rt-person_id` (`rt-person_id`),
KEY meta_key (meta_key)
) $charset_collate";
Now, call the function to create this table
require_once ABSPATH . 'wp-admin/includes/upgrade.php';
dbDelta( $sql );
As we are using this as a meta table we have to let the wpdb know about our meta table for that we can use
$table = 'rt-person_meta';
$wpdb->$table = $wpdb->prefix . 'rt-person_meta';
Ok, done with this, now we can use the already existing meta functions, just pass the post_type as our own like rt-movie or something.
It will then check for the entry of wp_rt-moviemeta in the wpdb, and if there is a table it will use that.
Will the meta query work though?
- I printed the query after creating the tables and it was somehow using the wp_postmeta table instead of our custom
- I had specified the
post_typebut it was taking it as justpost
Why does it not work?
I don’t really know for sure, but this could be the reason, so meta query uses the class WP_Meta_Query to generate the sql that will be added to the main sql to query the database accordingly.
Adding new role
We can have many use cases to add a new role to maange only specific post types and not all the others!, for that we can create new roles, custom capabilities and assign them,
To create a new role we can use the function add_role()
add_role(
'movie-manager',
__( 'Movie Manager', 'movie-library' ),
$capabilities
);
We should add this in plugin activation hook, as it should be called only once, We can also remove the role using function remove_role()
remove_role( 'movie-manager' );
We will add this in the plugin deactivation hook.
Leave a Reply