Dans l'administration Wordpress, par exemple sur la page d'édition d'un article, il peut être utile de remplacer les boutons checkbox des catégories par des boutons radio pour attribuer nos articles à une seule catégorie, au lieu des choix multiples que les cases à cocher permettaient.

<?php

class Boutons_Radio_Categories extends Walker{
    
    public $tree_type;
    
    public $db_fields = array('parent' => false, 'id' => 'term_id');
    
    
    public function __construct( $tree_type ){
        $this->tree_type = sanitize_text_field($tree_type);
    }
    

    public function start_el( &$output, $category, $depth = 0, $args = array(), $id = 0 ) {
        
        $taxonomy = $args['taxonomy'];
        
        $name = 'tax_input['.$taxonomy.']';
        
        $terms = get_terms(array('taxonomy' => $this->tree_type, 'hide_empty' => false, 'parent' => 0 ));
        
        foreach($terms as $cl => $term){
            
            if( $term->name == $category->name ){
                                
                $output .= '<li id="'.$taxonomy.'-'.$term->term_id.'">'.
                '<label class="selectit"><input value="'.$category->term_id.'" type="radio" name="'.$name.'[]" id="in-'.$taxonomy.'-'.$term->term_id.'"'.
                checked( in_array( $category->term_id, $args['selected_cats'] ), true, false ).
                disabled( empty( $args['disabled'] ), false, false ).'>'.esc_html( $term->name ).
                '</label></li>';
                
            }
        }
        
    }
    
}

Intégration de la class Boutons_Radio_Categorie

<?php

class Admin_Posts{

    public function __construct(){
        add_filter('wp_terms_checklist_args', array($this, 'boutons_radio_categories'), 100, 2);
    }

    public function boutons_radio_categories( $args, $post_id ){
        
        $post_types_tax = array(
            'infographie' => 'taxographies', 
            'animation' => 'taxanimes', 
            'post' => 'category'
        );
        $post_type = get_post_type($post_id);
        
        if( isset($post_types_tax[$post_type]) ){
            
            include_once(ADMINPATH.'admin/class-boutons-radio-categories.php');
            $args['walker'] = new Boutons_Radio_Categories($post_types_tax[$post_type]);
        }
        return $args;
    }
}

return new Admin_Posts();

Class Wordpress utilisée

Walker

Retour