walker()


WordPressのwalker()関数は、特定のHTML要素を生成するためにツリー構造のデータを処理する際に使用されます。主にナビゲーションメニューやカテゴリリストのレンダリングに役立ちます。

構文

class Walker {
    public function start_lvl(&$output, $depth = 0, $args = array()) {}
    public function end_lvl(&$output, $depth = 0, $args = array()) {}
    public function start_el(&$output, $object, $depth = 0, $args = array(), $id = 0) {}
    public function end_el(&$output, $object, $depth = 0, $args = array()) {}
}

引数の説明:

  • &$output (string) — 生成されたHTMLを保存する変数。
  • $depth (int) — 階層の深さを示す数値。
  • $args (array) — カスタマイズ用の追加引数。
  • $object (mixed) — 現在処理中の要素。
  • $id (int) — 要素のID。

使用例

例1. カスタムカテゴリリストのレンダリング

以下は、カスタムカテゴリリストを生成するコードです。

<?php
class Custom_Walker_Category extends Walker {
    public function start_el(&$output, $category, $depth = 0, $args = array(), $id = 0) {
        $output .= '<li>' . $category->name . '</li>';
    }
}
wp_list_categories(array('walker' => new Custom_Walker_Category()));
?>

例2. ナビゲーションメニューのカスタマイズ

ナビゲーションメニュー項目にカスタムクラスを追加します。

<?php
class Custom_Walker_Nav_Menu extends Walker {
    public function start_el(&$output, $item, $depth = 0, $args = array(), $id = 0) {
        $output .= '<li class="custom-class">' . $item->title . '</li>';
    }
}
wp_nav_menu(array('walker' => new Custom_Walker_Nav_Menu()));
?>

例3. 子要素のカスタムレンダリング

子要素リストの階層をカスタマイズします。

<?php
class Depth_Walker extends Walker {
    public function start_lvl(&$output, $depth = 0, $args = array()) {
        $output .= '<ul class="depth-' . $depth . '">';
    }
}
wp_nav_menu(array('walker' => new Depth_Walker()));
?>

例4. コメントリストの表示

コメントリストをカスタマイズする例です。

<?php
class Custom_Walker_Comment extends Walker {
    public function start_el(&$output, $comment, $depth = 0, $args = array(), $id = 0) {
        $output .= '<li>' . get_comment_author($comment) . '</li>';
    }
}
wp_list_comments(array('walker' => new Custom_Walker_Comment()));
?>

例5. ナビゲーションアイコンの追加

メニュー項目にアイコンを追加します。

<?php
class Icon_Walker extends Walker {
    public function start_el(&$output, $item, $depth = 0, $args = array(), $id = 0) {
        $output .= '<li><span class="icon"></span>' . $item->title . '</li>';
    }
}
wp_nav_menu(array('walker' => new Icon_Walker()));
?>

注意点

walker()を使用する際は、クラスの構造を正しく理解し、適切にオーバーライドしてください。特にHTML構造や出力形式に注意を払うことが重要です。


関連機能: