Skip to content

Instantly share code, notes, and snippets.

@alexandrtretyakov
Last active November 24, 2023 12:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save alexandrtretyakov/759fc3fbc2e8e445accaebcc06360387 to your computer and use it in GitHub Desktop.
Save alexandrtretyakov/759fc3fbc2e8e445accaebcc06360387 to your computer and use it in GitHub Desktop.
К статье Таблицы в админке Wordpress (часть 1) https://tretyakov.net/post/tabliczy-v-adminke-wordpress-chast-1/
<?php
/*
* Plugin Name: Сотрудники организации
* Description: Плагин для демонстрации работы класса WP_List_Table
* Version: 0.0.1
* Author: Александр Третьяков
* Author URI: https://tretyakov.net/
* License: GPLv2 or later
* License URI: https://www.gnu.org/licenses/gpl-2.0.html
*
*/
// Загружаем файл с классом WP_List_Table
if ( ! class_exists( 'WP_List_Table' ) ) {
require_once( ABSPATH . 'wp-admin/includes/class-wp-list-table.php' );
}
// Создаем наш класс, который наследует WP_List_Table
class Employees_List_Table extends WP_List_Table {
private $table_data;
// Создаем колонки нашей таблицы
function get_columns() {
$columns = array(
'cb' => '<input type="checkbox" />',
'name' => 'Имя',
'department' => 'Отдел',
'on_vacation' => 'Сотрудник в отпуске?'
);
return $columns;
}
function prepare_items() {
$this->table_data = $this->get_table_data();
$columns = $this->get_columns();
$hidden = array();
$sortable = array();
$primary = 'name';
$this->_column_headers = array( $columns, $hidden, $sortable, $primary );
$this->items = $this->table_data;
}
// Забираем данные из БД
private function get_table_data() {
global $wpdb;
$table = $wpdb->prefix . 'adt_employees_table';
return $wpdb->get_results(
"SELECT * from {$table}",
ARRAY_A
);
}
function column_default( $item, $column_name ) {
switch ( $column_name ) {
case 'id':
case 'name':
case 'department':
case 'on_vacation':
default:
return $item[ $column_name ];
}
}
function column_cb( $item ) {
return sprintf(
'<input type="checkbox" name="element[]" value="%s" />',
$item['id']
);
}
}
// Добавляем ссылку на плагин в меню админки
function my_add_menu_items() {
add_menu_page( 'Сотрудники организации', 'Сотрудники организации', 'activate_plugins', 'employees_list_table', 'employees_list_init' );
}
add_action( 'admin_menu', 'my_add_menu_items' );
function employees_list_init() {
// Создаем экземпляр класса Employees_List_Table
$table = new Employees_List_Table();
echo '<div class="wrap"><h2>Список сотрудников</h2>';
// Формируем таблицу
$table->prepare_items();
// Выводим таблицу
$table->display();
echo '</div>';
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment