Custom Metabox for Specific Category

There are various ways of handling metaboxes and post category types in WordPress. If time allows it’s often better for the clients if you can create custom post types for specific categories and then add in meta boxes specific for those post types.

Occasionally that can feel a bit heavyweight, depending on the application. A quicker and easier way to do it is to create a normal post category and then display your metabox only if the user checks that category in their post edit screen. We do this using Javascript, the essence of it being that technically speaking the metabox is created and sitting there all the time, it’s only displayed if the user checks the appropriate category.

The example below assumes that the post category is 7 (I’ve just pulled it straight from a site I’m doing) and there is a post category called Fee Guides;

/* JAVASCRIPT TO TOGGLE META BOX VISIBILITY IF WE ARE WORKING ON A FEE GUIDE POST  -----------------------------------------------------*/

function customadmin_feeguide() {
	if ( is_admin() ) {
		$script = "
			<script type='text/javascript'>
				jQuery(document).ready(function($) {
					$('#meta-feeguide-boxes').hide();
					$('#in-category-7').is(':checked') ? $('#meta-feeguide-boxes').show() : $('#meta-feeguide-boxes').hide();
					$('#in-category-7').click(function() {
						$('#meta-feeguide-boxes').toggle(this.checked);
					});
				});
		</script>";
		echo $script;
    }
}
add_action('admin_footer', 'customadmin_feeguide');