Limit selected categories to one in wordpress

if you need to limit the creator of posts in the number of selected categories to one then I have good news for you.

NOTE: This code just change checkbox to radio in category form and doesn't validate it in backend!

add_filter('wp_terms_checklist_args', 'htmlandcms_select_one_category');
function htmlandcms_select_one_category($args) {
	if (isset($args['taxonomy']) && $args['taxonomy'] == 'category_portfolio') {
		$args['walker'] = new Walker_Category_Radios;
		$args['checked_ontop'] = false;
	}
	return $args;
}

class Walker_Category_Radios extends Walker {
	var $tree_type = 'category';
	var $db_fields = array ('parent' => 'parent', 'id' => 'term_id'); 

	function start_lvl( &$output, $depth = 0, $args = array() ) {
		$indent = str_repeat("\t", $depth);
		$output .= "$indent<ul class='children'>\n";
	}

	function end_lvl( &$output, $depth = 0, $args = array() ) {
		$indent = str_repeat("\t", $depth);
		$output .= "$indent</ul>\n";
	}

	function start_el( &$output, $category, $depth, $args, $id = 0 ) {
		extract($args);
		if ( empty($taxonomy) )
			$taxonomy = 'category';

		if ( $taxonomy == 'category' )
			$name = 'post_category';
		else
			$name = 'tax_input['.$taxonomy.']';

		/** @var $popular_cats */
		$class = in_array( $category->term_id, $popular_cats ) ? ' class="popular-category"' : '';
		/** @var $selected_cats */
		$output .= "\n<li id='{$taxonomy}-{$category->term_id}'$class>" . '<label class="selectit"><input value="' . $category->term_id . '" type="radio" name="'.$name.'[]" id="in-'.$taxonomy.'-' . $category->term_id . '"' . checked( in_array( $category->term_id, $selected_cats ), TRUE, FALSE ) . disabled( empty( $args['disabled'] ), FALSE, FALSE ) . ' /> ' . esc_html( apply_filters('the_category', $category->name )) . '</label>';
	}

	function end_el( &$output, $category, $depth = 0, $args = array() ) {
		$output .= "</li>\n";
	}
}
Rating: 
8 out of 10 based on 6 ratings.
Tags: