0

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?

1 Answer 1

3

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];
    }
}
1
  • 1
    This was really helpful. Thanks!
    – Gavin
    Mar 25, 2023 at 9:26

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.