specific rows style for in custom list table using WP_List_Table

I am building a custom WordPress plugin where I create a custom list table for entities in a custom database table, extending the WP_List_Table class.

Everything works as expected but I want to style each row based on the value of a specific column of the row that is returned from the DB.

The iteration of the columns for each row happens inside the column_default() function:

/**
 * Render a column when no column specific method exists.
 *
 * @param array $item
 * @param string $column_name
 *
 * @return mixed
 */
public function column_default( $item, $column_name ) {
    
    switch ( $column_name ) {           
        case 'id':
            return $item[$column_name];
        default:
          return $item[$column_name];
    }
}

For example:

If the viw_status column of the current item that is printed on the list table equals 1 ($item['viw_status '] == 1), the current item's row must have green background color otherwise grey something.

Is there a any way to apply a custom css class to a row based on the values of its columns?

Topic wp-list-table plugin-development plugins Wordpress

Category Web


It depends where you want to apply your custom css class.

CSS class for table row

If you want to add the custom class to the <tr> element, I recommend to overwrite the function single_row like so:

public function single_row( $item ) {
    $cssClass = ($item['view_status '] == 1) ? 'make-it-green' : 'make-it-grey';
    echo '<tr class="'.$cssClass.'">';
    $this->single_row_columns( $item );
    echo '</tr>';
}

CSS class for table cell

Use the column_{column name} functions like you have outlined it with column_default and put a HTML tag as a wrapper within the cell. For example a span element:

public function column_default( $item, $column_name ) {
    $cssClass = ($item['view_status '] == 1) ? 'make-it-green' : 'make-it-grey';
    switch ( $column_name ) {           
        case 'id':
            return '<span class="'.$cssClass.'">'.$item[$column_name].'</span>';
        default:
          return $item[$column_name];
    }
}

About

Geeks Mental is a community that publishes articles and tutorials about Web, Android, Data Science, new techniques and Linux security.