I am trying to change the checkboxes for the terms on the backend to radiobuttons.
I found this topic: Altering the appearance of custom taxonomy inputs however wich helped me doing this.
However, this will turn ALL terms checkboxes to radio buttons.
Is it possible to apply this only for one taxonomy?
My code:
add_action('add_meta_boxes','mysite_add_meta_boxes',10,2);
function mysite_add_meta_boxes($post_type, $post) {
ob_start();
}
add_action('dbx_post_sidebar','mysite_dbx_post_sidebar');
function mysite_dbx_post_sidebar() {
$html = ob_get_clean();
$html = str_replace('"checkbox"','"radio"',$html);
echo $html;
}
thanks
4 s
However, this will turn ALL terms checkboxes to radio buttons.
Not only that, it’ll turn any checkbox in a meta box – not ideal!
Instead, let’s specifically target the wp_terms_checklist()
function, which is used to generate the list of checkboxes across the admin (including quick edit).
/**
* Use radio inputs instead of checkboxes for term checklists in specified taxonomies.
*
* @param array $args
* @return array
*/
function wpse_139269_term_radio_checklist( $args ) {
if ( ! empty( $args['taxonomy'] ) && $args['taxonomy'] === 'category' /* <== Change to your required taxonomy */ ) {
if ( empty( $args['walker'] ) || is_a( $args['walker'], 'Walker' ) ) { // Don't override 3rd party walkers.
if ( ! class_exists( 'WPSE_139269_Walker_Category_Radio_Checklist' ) ) {
/**
* Custom walker for switching checkbox inputs to radio.
*
* @see Walker_Category_Checklist
*/
class WPSE_139269_Walker_Category_Radio_Checklist extends Walker_Category_Checklist {
function walk( $elements, $max_depth, ...$args ) {
$output = parent::walk( $elements, $max_depth, ...$args );
$output = str_replace(
array( 'type="checkbox"', "type="checkbox"" ),
array( 'type="radio"', "type="radio"" ),
$output
);
return $output;
}
}
}
$args['walker'] = new WPSE_139269_Walker_Category_Radio_Checklist;
}
}
return $args;
}
add_filter( 'wp_terms_checklist_args', 'wpse_139269_term_radio_checklist' );
We hook onto the wp_terms_checklist_args
filter, then implement our own custom “walker” (a family of classes used to generate hierarchical lists). From there, it’s a simply string replace of type="checkbox"
with type="radio"
if the taxonomy is whatever we’ve configured it to match (in this case “category”).