0
0
Wordpressframework~30 mins

Plugin database tables in Wordpress - Mini Project: Build & Apply

Choose your learning style9 modes available
Create and Use Plugin Database Tables in WordPress
📖 Scenario: You are building a WordPress plugin that needs to store custom data in its own database table. This is common when plugins manage their own records, like events, contacts, or custom logs.
🎯 Goal: Build a WordPress plugin that creates a custom database table on activation and inserts data into it.
📋 What You'll Learn
Create a function to set up a custom database table named wp_custom_data with columns id (primary key, auto-increment) and info (text).
Use the WordPress dbDelta function to create or update the table.
Add an activation hook to run the table creation function.
Insert a sample row with info value 'Hello World' into the custom table.
💡 Why This Matters
🌍 Real World
Many WordPress plugins need their own tables to store custom data efficiently and separately from posts or options.
💼 Career
Understanding how to create and manage plugin database tables is essential for WordPress plugin developers and backend engineers working with WordPress.
Progress0 / 4 steps
1
Create the database table setup function
Write a function called create_custom_table that uses the global $wpdb variable and sets a variable $table_name to $wpdb->prefix . 'custom_data'. Define a SQL string $charset_collate using $wpdb->get_charset_collate(). Then create a SQL statement $sql to create a table with columns id as mediumint(9) NOT NULL AUTO_INCREMENT PRIMARY KEY and info as text NOT NULL. Use dbDelta to run the SQL.
Wordpress
Need a hint?

Remember to use dbDelta to create or update the table safely.

2
Add activation hook to create the table
Add a WordPress activation hook using register_activation_hook that calls the create_custom_table function when the plugin is activated. Use __FILE__ as the first argument.
Wordpress
Need a hint?

Use register_activation_hook with __FILE__ and the function name.

3
Insert a sample row into the custom table
Inside the create_custom_table function, after calling dbDelta, insert a new row into the $table_name table with the info column set to 'Hello World' using $wpdb->insert.
Wordpress
Need a hint?

Use $wpdb->insert with the table name and data array.

4
Complete the plugin file with header and closing PHP tag
Add the WordPress plugin header comment at the top of the file with Plugin Name: Custom Data Table. Also, ensure the PHP file ends properly without extra closing tags.
Wordpress
Need a hint?

The plugin header comment must be at the very top of the file.