31957
[![画像の説明をここに入力](https://i.stack.imgur.com/3gSLf.png)](https://i.stack.imgur.com/3gSLf.png)

Wordpressで`<?php wp_dropdown_categories();
?>`でカテゴリの選択画面を表示させた時に、サブカテゴリの前には「-」のような棒を表示して親カテゴリと分けたいです。
CC BY-SA 3.0
2017-01-17T13:22:19.273
31912
2017-01-18T22:04:31.487
2017-01-18T21:22:24.387
2376
9480
question
php wordpress
wp_dropdown_categories() でサブカテゴリの前に横棒を入れたい。
引数でどうにかするのも難しそうなので置換でやってみたものの少しアレ。

```

    function h_dopdown_cat() {
        echo preg_replace_callback( '/(<option[^>]*>)((?:&nbsp;)+)/u', function ( $matches ) {
            return $matches[1] . str_repeat( '–', strlen( $matches[2] ) / 18 ) . ' ';
        }, wp_dropdown_categories( [
            'echo'         => 0,
            'depth'        => 3,
            'hierarchical' => true
        ] ) );
    }
    
```

と思ったところ、 Walkerクラスを自前で用意すればなんとかなりそうとのこと。  
<https://developer.wordpress.org/reference/functions/wp_dropdown_categories/#comment-1823>

```

    class My_Walker_CategoryDropdown extends Walker_CategoryDropdown {
        public function start_el( &$output, $category, $depth = 0, $args = array(), $id = 0 ) {
            $pad = str_repeat( '-', $depth );
    
            /** This filter is documented in wp-includes/category-template.php */
            $cat_name = apply_filters( 'list_cats', $category->name, $category );
    
            if ( isset( $args['value_field'] ) && isset( $category->{$args['value_field']} ) ) {
                $value_field = $args['value_field'];
            } else {
                $value_field = 'term_id';
            }
    
            $output .= "\t<option class=\"level-$depth\" value=\"" . esc_attr( $category->{$value_field} ) . "\"";
    
            // Type-juggling causes false matches, so we force everything to a string.
            if ( (string) $category->{$value_field} === (string) $args['selected'] ) {
                $output .= ' selected="selected"';
            }
            $output .= '>';
            $output .= $pad . $cat_name;
            if ( $args['show_count'] ) {
                $output .= '&nbsp;&nbsp;(' . number_format_i18n( $category->count ) . ')';
            }
            $output .= "</option>\n";
        }
    
    }
    
    wp_dropdown_categories( [
        'depth'        => 3,
        'hierarchical' => true,
        'walker'       => new My_Walker_CategoryDropdown(),
    ] );
    
```

[![例](https://i.stack.imgur.com/nJ9r9.png)](https://i.stack.imgur.com/nJ9r9.png)
CC BY-SA 3.0
2017-01-18T22:04:31.487
31957
2017-01-18T22:04:31.487
2376
31912
answer