How to Create WP_List_Table in WordPress
To create a custom WP_List_Table in WordPress-
Create a Custom Class: Extend the `WP_List_Table
` class to create your custom table in a custom plugin or in your theme’s `functions.php
` file.
if ( ! class_exists( 'Custom_List_Table' ) ) {
class Custom_List_Table extends WP_List_Table {
function column_default( $item, $column_name ) {
return $item[ $column_name ];
}
function column_cb( $item) {
return sprintf(
'<input type="checkbox" name="bulk_delete[]" value="%s" />',
$item['ID']
);
}
function get_columns() {
$columns = array(
'cb' => '<input type="checkbox" />',
'ID' => 'ID',
'name' => 'Name',
'Email' => 'Email',
);
return $columns;
}
function prepare_items() {
$data = array(
array('ID' => 1, 'name' => 'John Doe', 'email' => 'john@example.com' ),
array('ID' => 2, 'name' => 'Jane Smith', 'email' => 'jane@example.com' )
);
$this->items = $data;
$this->set_pagination_args( array(
'total_items' => count( $data ),
'per_page' => 5
) );
}
}
}
Add Admin Menu: Add an admin menu item to display your custom table.
function my_plugin_menu() {
add_menu_page(
'Custom List Table',
'Custom Table',
'manage_options',
'custom-table',
'my_custom_table_page'
);
}
add_action( 'admin_menu', 'my_plugin_menu' );
function my_custom_table_page() {
$table = new Custom_List_Table();
$table->prepare_items();
?>
<div class="wrap">
<h2>Custom List Table</h2>
<form method="post">
<?php
$table->display();
?>
</form>
</div>
<?php
}
By extending a custom `WP_List_Table
` class created and add it to the WordPress admin menu. Adjust the table columns and data as needed for your specific use case.