6

When adding a metabox, i.e.:

add_meta_box( 
    'metabox_id',
    'Metabox Title',
    'my_metabox_callback',
    'page',
    'normal',
    'low', 
    array( 'foo' => $var1, 'bar' => $var2)
);

how do I add a class to it for css styling? I'd like to avoid having to call each id in the style rule for metaboxes that contain elements having the same style.

2 Answers 2

1

Just add the class to the markup you are generating in the callback.

1
  • simple, as there's no built-in way to do this yet. i'll just wrap my metabox content in a classd div. thanks, @KDM
    – Ana Ban
    Apr 22, 2012 at 3:01
17

Let's say you want a class for the excerpt box. Then you can do:

add_filter('postbox_classes_post_postexcerpt','add_metabox_classes');

function add_metabox_classes($classes) {
    array_push($classes,'another_class');
    return $classes;
}

With this method you need to add a filter for every box u need to add a class for. The filter is applied in the function postbox_classes in wp-admin/includes/post.php

In general the hook is postbox_classes_{$page}_{$id} where $page is the page identifier (e.g. 'post' for posts and (presumably) 'custom-post-type' for posts of type 'custom-post-type'). $id refers to the ID of the metabox, automatically assigned for 'default' metaboxes or specified in add_meta_box.

DOCS: https://developer.wordpress.org/reference/hooks/postbox_classes_page_id/

3
  • this is awesome. but i'd have to admit it'll be much simpler if i just wrap my metabox output in a classd div. thanks so much for the answer, though @offroff you rock.
    – Ana Ban
    Apr 22, 2012 at 3:00
  • 2
    +1. Just added the general hook. I've not look closely at the source code, but I believe the $page variable, at least for post-edit screens, is the post type. Apr 22, 2012 at 11:19
  • Yup can confirm when working on a custom post type that you need to supply the post type in place of {$page} - postbox_classes_posttype_metaboxid
    – rmorse
    Apr 11, 2015 at 16:53

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.