How to Add a Class to a Metabox

Code Sample Matrix

While developing a new plugin, I had needed to show/hide some metaboxes based on which radio button is selected from another metabox. Fortunately, I found this method and wanted to share my findings. You can see this method at the top of the gist below.

The add_filter() statement works like this: the {post_type_name} is exactly that, the name of your post type. In my plugin, it would be “slushman_portfolio”, but if you’re doing this with the built-in WordPress posts, it would “posts”. The {metabox_id} is the id attribute of the metabox for which you want to apply the filter.

The add_metabox_classes() function grabs the $classes array and adds your additional class to the end, then returns the array. When the metabox gets created, the $classes array contains all the classes that are put into the class attribute.

Now, you’re all finished. The class you want to add to your metabox is added. I’ll write another tutorial on how to use jQuery to show or hide that metabox based on the value of the radio buttons.

EDIT (4/7/2014):

I’ve recently updated this method in four ways to make it simpler and easier. First of all, the $classes parameter passed in from WordPress is an array, so make sure the parameter itself is optional by assigning it as a blank array if its empty. Second, create an array of the class or classes you’d like to add. Third, check the existing $classes array to make sure you don’t add a class that’s already in there. Fourth, instead of using the array_push function, just assign it to the next place in the $classes array using the brackets after the variable.

/**
* The simplistic way to add a custom class to a specific metabox
*
* @param array $classes The current classes on the metabox
* @return array The modified classes on the metabox
*/
function add_metabox_classes( $classes = array() ) {
return array_push( $classes, sanitize_html_class( 'my-custom-class' ) );
} // add_metabox_classes()
/**
* {post_type_name} The name of the post type
* {metabox_id} The ID attribute of the metabox
*/
add_filter( 'postbox_classes_{post_type_name}_{metabox_id}, 'add_metabox_classes' );
/**
* The more thorough way to add a custom class to a specific metabox
*
* Uses the same add_filter call, but its easier to add additional classes
* and it checks if new class is already there.
*
* @param array $classes The current classes on the metabox
* @return array The modified classes on the metabox
*/
function add_class( $classes = array() ) {
$add_classes = array( 'new_class1', 'new_class2' );
foreach ( $add_classes as $class ) {
if ( ! in_array( $class, $classes ) ) {
$classes[] = sanitize_html_class( $class );
}
} // End of foreach loop
return $classes;
} // add_class()

 

 

Leave a Reply