WordPress - Admin list table

From XennisWiki
Jump to: navigation, search

Use the WordPress private class WP_List_Table to create your own admin list table in the WordPress style, i.e. the following table with features like the pagination and the sortable columns:

WordPress - Admin list table.png

Code

Common class

<?php
/*
 * @see https://wordpress.org/plugins/custom-list-table-example/
 * @see http://www.smashingmagazine.com/2011/11/native-admin-tables-wordpress/
 */

/*
 * Load the base class
 */
if(!class_exists('WP_List_Table')){
	require_once( ABSPATH . 'wp-admin/includes/class-wp-list-table.php' );
}

abstract class Simple_WP_List_Table extends WP_List_Table {
	
	private $per_page = 5;
	
	function __construct($options, $per_page = NULL) {
		global $status, $page;
		
		//Set parent defaults
		parent::__construct($options);
		
		if ($per_page) {
			$this->per_page = $per_page;
		}
	}

	function column_default($item, $column_name){
		return $item[$column_name];
	}
	
	function column_cb($item){
		return '<input type="checkbox" name="'.$this->_args['singular'].'" value="'.$item['id'].'" />';
	}

	function prepare_items() {
		global $wpdb;

		/* -- Preparing your query -- */
		$query = "SELECT * FROM xb_spg_gallery";

		/* -- Ordering parameters -- */
		$orderby = !empty($_GET["orderby"]) ? mysql_real_escape_string($_GET["orderby"]) : 'ASC';
		$order = !empty($_GET["order"]) ? mysql_real_escape_string($_GET["order"]) : '';
		if(!empty($orderby) & !empty($order)){ $query.=' ORDER BY '.$orderby.' '.$order; }

		/* -- Pagination parameters -- */
		//Number of elements in your table?
		$total_items = $wpdb->query($query); //return the total number of affected rows
		//Which page is this?
		$paged = !empty($_GET["paged"]) ? mysql_real_escape_string($_GET["paged"]) : '';
		//Page Number
		if(empty($paged) || !is_numeric($paged) || $paged<=0 ){ $paged=1; }
		//adjust the query to take pagination into account
		if(!empty($paged)){
			$offset=($paged-1)*$this->per_page;
			$query.=' LIMIT '.(int)$offset.','.(int)$this->per_page;
		}
			
		// Register the pagination
		$current_page = $this->get_pagenum();
		$this->set_pagination_args( array(
			'total_items' => $total_items,
			'total_pages' => ceil($total_items/$this->per_page),
			'per_page' => $this->per_page,
		) );

		// Register the columns
		$columns = $this->get_columns();
		$hidden = array();
		$sortable = $this->get_sortable_columns();
		$this->_column_headers = array($columns, $hidden, $sortable);		   

		// Bulk action
		$this->process_bulk_action();
		
		// Fetch item
		$this->items = $wpdb->get_results($query, 'ARRAY_A');
	}
	
	function display() {
		?>
		<form method="get">
			<input type="hidden" name="page" value="<?php echo $_REQUEST['page'] ?>" />
			<?php parent::display(); ?>
		</form>
		<?php
	}
}

Specific class

<?php
class Gallery_List_Table extends Simple_WP_List_Table {
	
	/**
	* Constructor, we override the parent to pass our own arguments
	* We usually focus on three parameters: singular and plural labels, as well as whether the class supports AJAX.
	*/
	function __construct() {
		parent::__construct(array(
			'singular'  => 'gallery',     //singular name of the listed records
			'plural'    => 'galleries',    //plural name of the listed records
			'ajax'      => false        //does this table support ajax?
		), 5);
	}

	/**
	 * Define the columns that are going to be used in the table
	 * @return array $columns, the array of columns to use with the table
	 */
	function get_columns() {
		return array(
			'cb' => '<input type="checkbox" />', //Render a checkbox instead of text
			'name' => __('Name'),
			'slug' => __('Slug'),		   
			'description ' => __('Description')
		);
	}

	/**
	 * Decide which columns to activate the sorting functionality on
	 * @return array $sortable, the array of columns that can be sorted by the user
	 */
	public function get_sortable_columns() {
		return array(
			'name' => array('name'),
			'slug' => array('slug')
		);
	}
	
	function column_name($item){

		//Build row actions
		$actions = array(
			'edit'      => '<a href="?page='.$_REQUEST['page'].'&action=edit&gallery='.$item['id'].'">Edit</a>',
			'delete'    => '<a href="?page='.$_REQUEST['page'].'&action=delete&gallery='.$item['id'].'">Delete</a>'
		);

		//Return the title contents
		return $item['name'].' '.$this->row_actions($actions);
	}	
/*	
	function get_bulk_actions() {
		$actions = array(
			'delete'    => 'Delete'
		);
		return $actions;
	}	
	
	function process_bulk_action() {

		//Detect when a bulk action is being triggered...
		if( 'delete'===$this->current_action() ) {
			wp_die('Items deleted (or they would be if we had items to delete)!');
		}
	}
*/
}

Usage

<?php
// ...
$listTable = new Gallery_List_Table();
$listTable->prepare_items();
?>
<div class="wrap">
    <h2>Galleries <a href="" class="add-new-h2">Add New</a></h2>
    <?php $listTable->display(); ?>
</div>

See also

External links