gschoppe
2/28/2016 - 1:07 AM

Use category (checkbox-based) interface with non-hierarchical custom taxonomies

Use category (checkbox-based) interface with non-hierarchical custom taxonomies

<?php

// Event taxonomies
add_action( 'init', function() {
	$labels = array(
		'name'              => _x( 'Terms', 'taxonomy general name' ),
		'singular_name'     => _x( 'Term', 'taxonomy singular name' ),
	);
	register_taxonomy( 'taxonomy_name', array( 'post' ), array(
		'hierarchical'      => false,
		'labels'            => $labels,
		'meta_box_cb'       => "post_categories_meta_box",
	) );
} );

add_action( 'admin_head', function() {
	?>
	<style type="text/css">
		#newtaxonomy_name_parent {
			display: none;
		}
	</style>
	<?php
});
add_action( 'admin_init', function() {
	if( isset( $_POST['tax_input'] ) && is_array( $_POST['tax_input'] ) ) {
		$new_tax_input = array();
		foreach( $_POST['tax_input'] as $tax => $terms) {
			if( is_array( $terms ) ) {
			  $taxonomy = get_taxonomy( $tax );
			  if( !$taxonomy->hierarchical ) {
				  $terms = array_map( 'intval', array_filter( $terms ) );
			  }
			}
			$new_tax_input[$tax] = $terms;
		}
		$_POST['tax_input'] = $new_tax_input;
	}
});