現在のカテゴリーの孫カテゴリーも含めた子孫カテゴリーをリスト表示する。

Pocket

現在の表示されているカテゴリーの(孫カテゴリーを含めた)子孫カテゴリーのリストを返す。

テンプレートタグwp_list_categoriesは(孫カテゴリーを含まない)子カテゴリーのみを表示する。

global $cat; // 表示カテゴリーID
wp_list_categories('child_of=' . $cat); // 表示カテゴリーの子カテゴリーリスト

本記事の下記サンプルは孫カテゴリーも含めた子孫カテゴリーを表示する。

ファイル構成
examplet-theme
    |
    |- functions.php
    |-- ....
    |-- inc
          |-- category-hierarchy.php
          |-- widget.php
category-hierarchy.php
<?php
/**
 * 基準カテゴリーをベースに様々なカテゴリーIDの配列を保持する。
 *
 * @author Sawai Hiroshi
 */
class HierarchyCategory {

    // 基準カテゴリーID
    private $base_id;
    // 出力HTML
    private $output = '';

    /**
     * @constructor
     * @throws InvalidArgumentException 引数がカテゴリーIDでない
     */
    public function __construct($cat_id) {
        $all_cat_ids = get_all_category_ids();
        if (false === in_array(intVal($cat_id), $all_cat_ids)) {
            throw new InvalidArgumentException('argument  is not category id');
        };
        $this->base_id = $cat_id;
    }

    /**
     * 基準カテゴリーの(孫要素を除く)子カテゴリーID配列を返す
     *
     * @param $cat_id カテゴリーID
     * @throws InvalidArgumentException 引数がカテゴリーIDでない
     * @return array $child_ids (孫要素を含まない)子要素のカテゴリーIDの配列(自身は含まない)
     */
    private function getChildIds($cat_id) {
        $all_cat_ids = get_all_category_ids();
        if (false === in_array(intVal($cat_id), $all_cat_ids)) {
            throw new InvalidArgumentException('argument  is not category id');
        };
        $descendant_ids = get_term_children($cat_id, 'category');
        $child_ids = array();
        for ($i = 0; $i < count($descendant_ids); $i++) {
            $category = get_category($descendant_ids[$i]);
            if ($cat_id == $category->parent) {
                array_push($child_ids, $descendant_ids[$i]);
            }
        }
        return $child_ids;
    }

    /**
     * 子孫カテゴリーをHTMLUlElementで出力
     * @param $cat_id カテゴリーID
     * @return string 出力用HTML
     * @throws InvalidArgumentException 引数がカテゴリーIDでない
     */
    private function makeDescendantHtml($cat_id) {
        $all_cat_ids = get_all_category_ids();
        if (false === in_array(intVal($cat_id), $all_cat_ids)) {
            throw new InvalidArgumentException('argument  is not category id');
        }
        $child_ids =  $this->getChildIds($cat_id);
        if (count($child_ids) === 0) {
            $this->output .= '<li><a href="' . get_category_link($cat_id) . '">' . get_category($cat_id)->name . '</a></li>';
        } else {
            $this->output .= '<li><a href="' . get_category_link($cat_id) . '">' . get_category($cat_id)->name . '</a>';
            for ($i = 0; $i < count($child_ids); $i++) {
                if ($i === 0) {
                    $this->output .= '<ul>';
                }
                $this->makeDescendantHtml($child_ids[$i]);
                if ($i === count($child_ids) - 1) {
                    $this->output .= '</li></ul>';
                }
            }
        }
        return $this->output;
    }

    /**
     * 基準カテゴリーの子孫カテゴリーリストを出力
     * @return string 出力用HTML
     */
    public function getDescendant() {
        $child_ids = $this->getChildIds($this->base_id);
        if (count($child_ids) > 0) {
            $this->output .= '<ul>';
            for ($i = 0; $i < count($child_ids); $i++) {
                $this->makeDescendantHtml($child_ids[$i]);
            }
            $this->output .= '</ul>';
            return $this->output;
        }
    }
}
widget.php
<?php
/**
 * 子孫カテゴリー表示ウィジェット
 * @author Sawai Hiroshi
 */
class DescendantCategoryWidget extends WP_Widget {
    /** constructor */
    function DescendantCategoryWidget() {
        parent::WP_Widget(false, $name = 'DescendantCategoryWidget');
    }

    /** @see WP_Widget::widget */
    function widget($args, $instance) {
        if (is_category()) {
            global $cat;
            $category = get_category($cat);
            try {
                $hierarchy = new HierarchyCategory($cat);
            } catch (Exception $e) {
                echo $e->getMessage();
                exit;
            }
            echo ('<h2><a href="' . esc_url(get_category_link($category->cat_ID)) . '">' . esc_html($category->name) . '</a></h2>');
            echo $hierarchy->getDescendant();
        }
    }

    /** @see WP_Widget::update */
    function update($new_instance, $old_instance) {
        // nothing
    }

    /** @see WP_Widget::form */
    function form($instance) {
        // nothing
    }
}
functions.php
// include*
include( TEMPLATEPATH . '/inc/hierarchy-category.php' );
include( TEMPLATEPATH . '/inc/descendant-category-widget.php' );

/**
 * Widget
 */
add_action('widgets_init', create_function('', 'return register_widget("DescendantCategoryWidget");'));

» Gist

孫カテゴリー除いた直接の子カテゴリーのIDを取得する方法

基準となるカテゴリーの直接の子カテゴリーのIDを取得する。

  1. 基準とするカテゴリーIDのすべての子孫のカテゴリーIDの配列を取得する
  2. 1で取得した子孫カテゴリーIDの中で基準カテゴリーIDを親カテゴリーIDに持つものを抽出する。

上記のように抽出したカテゴリーIDは基準カテゴリーの直接の子カテゴリーのIDの配列。

基準カテゴリーID: $cat_id
子孫カテゴリーID配列: $descendant_ids
直接の子カテゴリーID配列

子孫のカテゴリーIDを全て配列として取得
$descendant_ids = get_term_children($cat_id, 'category');
子孫カテゴリーIDのなかで直接の子カテゴリーIDを抽出
$child_ids = array();
for ($i = 0; $i < count($descendant_ids); $i++) {
    $category = get_category($descendant_ids[$i]);
    if ($cat_id == $category->parent) {
        array_push($child_ids, $descendant_ids[$i]);
    }
}

コメント

No comments yet.

コメントの投稿

改行と段落タグは自動で挿入されます。
メールアドレスは表示されません。