Advertisement
MoonWatch

WordPress List Table class with conditional HTML classess

Nov 13th, 2012
1,204
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 10.07 KB | None | 0 0
  1. <?php
  2. class TT_Example_List_Table extends WP_List_Table {
  3.  
  4.     var $example_data = array(
  5.             array(
  6.                 'ID'        => 1,
  7.                 'title'     => '300',
  8.                 'rating'    => 'R',
  9.                 'director'  => 'Zach Snyder'
  10.             ),
  11.             array(
  12.                 'ID'        => 2,
  13.                 'title'     => 'Eyes Wide Shut',
  14.                 'rating'    => 'R',
  15.                 'director'  => 'Stanley Kubrick'
  16.             ),
  17.             array(
  18.                 'ID'        => 3,
  19.                 'title'     => 'Moulin Rouge!',
  20.                 'rating'    => 'PG-13',
  21.                 'director'  => 'Baz Luhrman'
  22.             ),
  23.             array(
  24.                 'ID'        => 4,
  25.                 'title'     => 'Snow White',
  26.                 'rating'    => 'G',
  27.                 'director'  => 'Walt Disney'
  28.             ),
  29.             array(
  30.                 'ID'        => 5,
  31.                 'title'     => 'Super 8',
  32.                 'rating'    => 'PG-13',
  33.                 'director'  => 'JJ Abrams'
  34.             ),
  35.             array(
  36.                 'ID'        => 6,
  37.                 'title'     => 'The Fountain',
  38.                 'rating'    => 'PG-13',
  39.                 'director'  => 'Darren Aronofsky'
  40.             ),
  41.             array(
  42.                 'ID'        => 7,
  43.                 'title'     => 'Watchmen',
  44.                 'rating'    => 'R',
  45.                 'director'  => 'Zach Snyder'
  46.             )
  47.         );
  48.  
  49.     /**
  50.     * A set of conditional classes
  51.     * you can add more stuff when you get the data in TT_Example_List_Table::prepare_elements()
  52.     *
  53.     * The data is stored as a (optionally)multi-dimensional key=>pair array.
  54.     *
  55.     * Only two top-level keys are reserved - "odd" and "even" - put your conditional classes for odd and even rows
  56.     * The other top-level keys could be column id's(like "title" for instance) or item ID's
  57.     * Each top-level key can hold either an array or a string
  58.     * If the top-level key holds a string, then when this condition is met, that class is added
  59.     * If the top-level key holds an array, then it's looped through.
  60.     * The second-level array can have string values and key=>value pairs, where the key is the class and the value
  61.     * is an array of conditions.
  62.     *
  63.     * I guess that's quite confusing, but the example bellow should give you an idea of how this works.
  64.     */
  65.     var $cond_classes = array(
  66.         'odd' => array(
  67.             'odd-class', // This class will always be given to odd rows and their columns
  68.             'special-odd-class' => array( // This class will only be given to odd rows and their columns if the rows is for an item with ID 1, 4 or 7
  69.                 'ID' => array( 1, 4, 7 )
  70.             )
  71.         ),
  72.         'even' => array(
  73.             'even-class'
  74.         ),
  75.         'title' => array(
  76.             'custom_title_class',
  77.             'special_title_class' => array(
  78.                 'ID' => array( 3, 7 ), // This will only be given to the "title" column for an item with ID 3 or 7
  79.                 'title' => 'The Fountain', // This will only be given to the "title" column for an item with title "The Fountain"
  80.             ),
  81.         ),
  82.         7 => 'id_7_class', // This will be given to a row and it's columns for item with ID 7
  83.     );
  84.  
  85.     function __construct(){
  86.         global $status, $page;
  87.  
  88.         //Set parent defaults
  89.         parent::__construct( array(
  90.             'singular'  => 'movie',     //singular name of the listed records
  91.             'plural'    => 'movies',    //plural name of the listed records
  92.             'ajax'      => false        //does this table support ajax?
  93.         ) );
  94.  
  95.     }
  96.  
  97.  
  98.     function column_default($item, $column_name){
  99.         switch($column_name){
  100.             case 'rating':
  101.             case 'director':
  102.                 return $item[$column_name] . 'hi';
  103.             default:
  104.                 return print_r($item,true) . ' hi'; //Show the whole array for troubleshooting purposes
  105.         }
  106.     }
  107.  
  108.  
  109.     function column_title($item){
  110.  
  111.         //Build row actions
  112.         $actions = array(
  113.             'edit'      => sprintf('<a href="?page=%s&action=%s&movie=%s">Edit</a>',$_REQUEST['page'],'edit',$item['ID']),
  114.             'delete'    => sprintf('<a href="?page=%s&action=%s&movie=%s">Delete</a>',$_REQUEST['page'],'delete',$item['ID']),
  115.         );
  116.  
  117.         //Return the title contents
  118.         return sprintf('%1$s <span style="color:silver">(id:%2$s)</span>%3$s',
  119.             /*$1%s*/ $item['title'],
  120.             /*$2%s*/ $item['ID'],
  121.             /*$3%s*/ $this->row_actions($actions)
  122.         );
  123.     }
  124.  
  125.  
  126.     function column_cb($item){
  127.         return sprintf(
  128.             '<input type="checkbox" name="%1$s[]" value="%2$s" />',
  129.             /*$1%s*/ $this->_args['singular'],  //Let's simply repurpose the table's singular label ("movie")
  130.             /*$2%s*/ $item['ID']                //The value of the checkbox should be the record's id
  131.         );
  132.     }
  133.  
  134.  
  135.     function get_columns(){
  136.         $columns = array(
  137.             'cb'        => '<input type="checkbox" />', //Render a checkbox instead of text
  138.             'title'     => 'Title',
  139.             'rating'    => 'Rating',
  140.             'director'  => 'Director'
  141.         );
  142.         return $columns;
  143.     }
  144.  
  145.  
  146.     function get_sortable_columns() {
  147.         $sortable_columns = array(
  148.             'title'     => array('title',true),     //true means its already sorted
  149.             'rating'    => array('rating',false),
  150.             'director'  => array('director',false)
  151.         );
  152.         return $sortable_columns;
  153.     }
  154.  
  155.  
  156.     function get_bulk_actions() {
  157.         $actions = array(
  158.             'delete'    => 'Delete'
  159.         );
  160.         return $actions;
  161.     }
  162.  
  163.  
  164.     function process_bulk_action() {
  165.  
  166.         //Detect when a bulk action is being triggered...
  167.         if( 'delete'===$this->current_action() ) {
  168.             wp_die('Items deleted (or they would be if we had items to delete)!');
  169.         }
  170.  
  171.     }
  172.  
  173.  
  174.     function prepare_items() {
  175.  
  176.  
  177.         $per_page = 10;
  178.  
  179.  
  180.         $columns = $this->get_columns();
  181.         $hidden = array();
  182.         $sortable = $this->get_sortable_columns();
  183.  
  184.  
  185.         $this->_column_headers = array($columns, $hidden, $sortable);
  186.  
  187.  
  188.         $this->process_bulk_action();
  189.  
  190.  
  191.         $data = $this->example_data;
  192.  
  193.  
  194.         function usort_reorder($a,$b){
  195.             $orderby = (!empty($_REQUEST['orderby'])) ? $_REQUEST['orderby'] : 'title'; //If no sort, default to title
  196.             $order = (!empty($_REQUEST['order'])) ? $_REQUEST['order'] : 'asc'; //If no order, default to asc
  197.             $result = strcmp($a[$orderby], $b[$orderby]); //Determine sort order
  198.             return ($order==='asc') ? $result : -$result; //Send final sort direction to usort
  199.         }
  200.         usort($data, 'usort_reorder');
  201.  
  202.  
  203.  
  204.         $current_page = $this->get_pagenum();
  205.  
  206.  
  207.         $total_items = count($data);
  208.  
  209.  
  210.  
  211.         $data = array_slice($data,(($current_page-1)*$per_page),$per_page);
  212.  
  213.  
  214.  
  215.         $this->items = $data;
  216.  
  217.  
  218.         $this->set_pagination_args( array(
  219.             'total_items' => $total_items,                  //WE have to calculate the total number of items
  220.             'per_page'    => $per_page,                     //WE have to determine how many items to show on a page
  221.             'total_pages' => ceil($total_items/$per_page)   //WE have to calculate the total number of pages
  222.         ) );
  223.     }
  224.  
  225.     /**
  226.      * Generate the table rows
  227.      *
  228.      * @since 3.1.0
  229.      * @access protected
  230.      */
  231.     function display_rows() {
  232.         foreach ( $this->items as $i => $item )
  233.             $this->single_row( $item, ( ( $i + 1 ) % 2 == 0 ? true : false ) );
  234.     }
  235.  
  236.     /**
  237.      * Generates content for a single row of the table
  238.      *
  239.      * @since 3.1.0
  240.      * @access protected
  241.      *
  242.      * @param object $item The current item
  243.      */
  244.     function single_row( $item, $even ) {
  245.         $classes = $this->get_cond_classes( $item, $even );
  246.         $row_class = ! empty( $classes ) ? ' class="' . implode( ' ', $classes ) . '"' : '';
  247.  
  248.         echo '<tr' . $row_class . '>';
  249.         echo $this->single_row_columns( $item, $even );
  250.         echo '</tr>';
  251.     }
  252.  
  253.     /**
  254.      * Generates the columns for a single row of the table
  255.      *
  256.      * @since 3.1.0
  257.      * @access protected
  258.      *
  259.      * @param object $item The current item
  260.      */
  261.     function single_row_columns( $item, $even ) {
  262.         list( $columns, $hidden ) = $this->get_column_info();
  263.  
  264.         foreach ( $columns as $column_name => $column_display_name ) {
  265.             $classes = 'cb' == $column_name ? array( 'check-column' ) : array( $column_name, "column-$column_name" );
  266.             $classes = array_merge( $classes, $this->get_cond_classes( $item, $even, $column_name ) );
  267.             $class = ! empty( $classes ) ? ' class="' . implode( ' ', $classes ) . '"' : '';
  268.  
  269.             $style = '';
  270.             if ( in_array( $column_name, $hidden ) )
  271.                 $style = ' style="display:none;"';
  272.  
  273.             $attributes = "$class$style";
  274.  
  275.             if ( 'cb' == $column_name ) {
  276.                 echo '<th scope="row"' . $attributes . '>';
  277.                 echo $this->column_cb( $item );
  278.                 echo '</th>';
  279.             }
  280.             elseif ( method_exists( $this, 'column_' . $column_name ) ) {
  281.                 echo "<td $attributes>";
  282.                 echo call_user_func( array( &$this, 'column_' . $column_name ), $item );
  283.                 echo "</td>";
  284.             }
  285.             else {
  286.                 echo "<td $attributes>";
  287.                 echo $this->column_default( $item, $column_name );
  288.                 echo "</td>";
  289.             }
  290.         }
  291.     }
  292.  
  293.     // Gets conditional classes for $item in either a row/column
  294.     function get_cond_classes( $item, $even, $column_name = false ) {
  295.         $classes = array();
  296.  
  297.         if ( $even ) {
  298.             // Check to see if there is a conditional class for even columns
  299.             if ( isset( $this->cond_classes['even'] ) ) {
  300.                 $this->parse_cond_classes( $item, $this->cond_classes['even'], $classes );
  301.             }
  302.         } else {
  303.             // Check to see if there is a conditional class for odd columns
  304.             if ( isset( $this->cond_classes['odd'] ) ) {
  305.                 $this->parse_cond_classes( $item, $this->cond_classes['odd'], $classes );
  306.             }
  307.             // This class is applied by default
  308.             $classes[] = 'alternate';
  309.         }
  310.  
  311.         // Check to see if there is a conditional class for the current column
  312.         if ( $column_name && isset( $this->cond_classes[ $column_name ] ) ) {
  313.             $this->parse_cond_classes( $item, $this->cond_classes[ $column_name ], $classes );
  314.         }
  315.  
  316.         // Check to see if there is a conditional class for the current element
  317.         if ( isset( $this->cond_classes[ $item['ID'] ] ) ) {
  318.             $this->parse_cond_classes( $item, $this->cond_classes[ $item['ID'] ], $classes );
  319.         }
  320.  
  321.         return $classes;
  322.     }
  323.  
  324.     // Parses the conditionals.
  325.     // $classess is passed by reference, so we directly edit that
  326.     function parse_cond_classes( $item, $to_parse, &$classes ) {
  327.         // If this is an array, loop through it and check conditions
  328.         if ( is_array( $to_parse ) ) {
  329.             foreach ($to_parse as $key => $data) {
  330.                 // If this is an array as well - we have more conditions
  331.                 if ( is_array( $data ) ) {
  332.                     foreach ($data as $_key => $_value) {
  333.                         if ( isset( $item[ $_key ] ) ) {
  334.                             if ( ( is_array( $_value ) && in_array( $item[ $_key ], $_value ) ) || $item[ $_key ] == $value ) {
  335.                                 $classes[] = $key;
  336.                             }
  337.                         }
  338.                     }
  339.                 } else {
  340.                     // Otherwise just add the class
  341.                     $classes[] = $data;
  342.                 }
  343.             }
  344.         } elseif ( $to_parse != '' ) {
  345.             // In case we only have one class for this condition
  346.             $classes[] = $to_parse;
  347.         }
  348.     }
  349. }
  350. ?>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement