Notice: Function _load_textdomain_just_in_time was called incorrectly. Translation loading for the wck domain was triggered too early. This is usually an indicator for some code in the plugin or theme running too early. Translations should be loaded at the init action or later. Please see Debugging in WordPress for more information. (This message was added in version 6.7.0.) in /home/cosmeanu/public_html/wp/wp-includes/functions.php on line 6114
Cosmeanu Costin - WordPress custom metaboxes class for custom themes

WordPress custom metaboxes class for custom themes

For WordPress plugin developers, the metabox API generally proves to be invaluable. Meta boxes allow you to organize various bits of information, groups of options and more into nice, attractive, collapsible boxes rather easily. What’s more, these boxes can be dragged around the screen and reorganized without much hassle. However, one thing that you can’t do with meta boxes is to assign additional CSS classes to them.

However, in WordPress 3.2, you will be able to do just that. WordPress 3.2 will introduce a brand new filter that allows you to modify the list of classes that are applied to a meta box. Unfortunately, the code syntax is somehow ambiguous, at least for recursive code ( eq. for more than one metabox ) .

Of course that if you add you metaboxes manually, the code is pretty straight-forward. But if you have more than one post type and more than one metabox to add to your theme, this can become tedious work in no time.

So let me explain my empiric found method :

I have based my metaboxes engine on this tutorial, so explaining the prerequisites is beyond the purpose of this bit and can be understood by any junior wordpress themes dev.

Here is my code for adding metaboxes recursively :

//Add meta boxes to post types
function theme_add_post_box() {

global $meta_box;

 foreach($meta_box as $post_type => $value) {

  $val = $value['id'];
  add_meta_box($value['id'], $value['title'], 'theme_format_post_box', $post_type, $value['context'], $value['priority']);
  add_filter( "postbox_classes_{$post_type}_{$val}", 'add_metabox_classes' );

 }

}

All the magic happens in this piece of code

postbox_classes_{$post_type}_{$val}

Provided that $post_type and $val are defined correctly, the hook will activate for every metabox. This will translate into “postbox_classes_my-post-type_my-metabox-id” in that foreach loop. That’s why $post_type and $ val need to be defined within the function that adds the metabox or within the foreach loop.

Now all we need to do is to write the hook function where we can define the actual class or classes we want to add :

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

So here you go, for every metabox added this way you can have a hook to add some more classes for extra styling.

Note : snippet developed from htmlcenter.com