June
June

Reputation: 823

Add Class to Custom Post type list page on WordPress dashboard

I am trying to add a class to each row in a WordPress custom post type list page, e.g. to add a class based on value of meta field for each post on backend:

For example: I have a feature “call enable/disable” – if the post is disabled (i.e. only viewable by certain user), the whole row should have a certain background color.

So I am looking for a solution to add a CSS class based upon meta field value.

Upvotes: 2

Views: 3614

Answers (3)

Arthur Shlain
Arthur Shlain

Reputation: 1109

functions.php

function my_post_class($classes, $class, $post_id){
    $slug = get_post_field( 'post_name', $post_id );
    $wrong_slug = false;
    if(strpos($slug, '%') !== false){
        $wrong_slug = true;
    }
    if(is_numeric(substr($slug, -1))){
        $wrong_slug = true;
    }
    if($wrong_slug){
        $classes[] = 'wrong-slug';
    }
    return $classes;
}
add_filter('post_class', 'my_post_class', 10, 3);

function admin_style() {
    wp_enqueue_style('admin-styles', get_template_directory_uri().'/admin.css');
}
add_action('admin_enqueue_scripts', 'admin_style');

admin.css

tr.wrong-slug th, tr.wrong-slug td {
  background-color: #FFCC99;
}

Upvotes: 0

jakubd
jakubd

Reputation: 11

Just in case brasofilo´s example gives you Missing argument warning, you can use the filter in the old way:

add_filter('post_class', 'name_of_your_function');

Then you have to define the function. In this example, I give each row a class with the ID of the post:

function name_of_your_function($classes)
{
    global $post;   
    $classes[] = 'post-id-' . $post->ID;
    return $classes;
}

Upvotes: 1

brasofilo
brasofilo

Reputation: 26065

I'll leave you with the material to mash this up.

For one, inspect the post classes,


We can change them with:

add_action( 'load-edit.php', function(){
    global $typenow; // current post type
    add_filter( 'post_class', function( $classes, $class, $postID ) {
        $classes[] = 'stack';
        return $classes;
    });
});

To print CSS, use:

add_action( 'admin_head-edit.php', function(){
    $color = 'FDFBC8';
    if( isset( $_GET['color'] ) )
        $color = $_GET['color'];
    ?>
    <style>
    tr.category-uncategorized {
        background-color: #<?php echo $color; ?> !important;
    }
    tr.stack {
        background-color: #333;
    }
    </style>
    <?php
});

This example looks for ?color=hexval in the URL:


You'll get your meta data with the $postID in the filter post_class.

Upvotes: 6

Related Questions