🎓 WordPress Plugin Development Tutorial (Modules 1–5)
Learn to build WordPress plugins step-by-step. Each module includes real working code examples, Prism.js highlighting, and glowing animated progress bars.
🧩 Module 5: Custom Admin Tables (Listing Plugin Data)
Let’s learn how to show stored plugin data inside a custom admin table.
Step 1: Create a Table on Plugin Activation
register_activation_hook(__FILE__, 'mfp_create_table');
function mfp_create_table() {
global $wpdb;
$table_name = $wpdb->prefix . 'mfp_records';
$charset_collate = $wpdb->get_charset_collate();
$sql = "CREATE TABLE $table_name (
id mediumint(9) NOT NULL AUTO_INCREMENT,
name varchar(100) NOT NULL,
created datetime DEFAULT CURRENT_TIMESTAMP NOT NULL,
PRIMARY KEY (id)
) $charset_collate;";
require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
dbDelta($sql);
}
Step 2: Add Sample Data (Optional)
function mfp_insert_sample_data() {
global $wpdb;
$table = $wpdb->prefix . 'mfp_records';
$wpdb->insert($table, ['name' => 'First Entry']);
$wpdb->insert($table, ['name' => 'Second Entry']);
}
add_action('admin_init', 'mfp_insert_sample_data');
Step 3: Display Data in Admin Table
function mfp_admin_page_html() {
global $wpdb;
$table = $wpdb->prefix . 'mfp_records';
$results = $wpdb->get_results("SELECT * FROM $table");
?>
<div class="wrap">
<h1>My Plugin Data Table</h1>
<table class="widefat fixed">
<thead><tr><th>ID</th><th>Name</th><th>Created</th></tr></thead>
<tbody>
<?php foreach ($results as $row): ?>
<tr>
<td><?php echo esc_html($row->id); ?></td>
<td><?php echo esc_html($row->name); ?></td>
<td><?php echo esc_html($row->created); ?></td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
</div>
<?php
}
✅ Now, your plugin can create a custom database table and display records inside the WordPress Admin area!
No comments:
Post a Comment