技術情報

wp_list_categoriesの記事数の表示をaタグの中にいれる方法

2016.07.15


wp_list_categoriesはカテゴリの一覧を各カテゴリのリンク付きで表示できる関数ですが、show_countオプションで投稿数を表示する事ができます。でもなぜか 各リンクの<a>タグの外に(1)等と表示されてしまします。

memo20160715a

これがコーダーさん的には良くないらしく、毎回修正して <a>タグの中にカテゴリと一緒にいいれています。

この対処方法を探すといろいろと方法が出ているのですが、

この記事では汎用性がありそうなWalker_Categoryを継承したクラスを作り、walkオプションに設定する手法をご紹介します。
functions.phpの中で、例えばclass Walker_Category_Linkin_Postcountという名前で下記のようにクラスを作成します。

class Walker_Category_Linkin_Postcount  extends Walker_Category {
}

次に wp-includes/class-walker-category.php の中の
start_el のメソッドの中をごっそり全部持ってきて、
最後の方にshow_countオプションなる下記の記述、

 if ( ! empty( $args['show_count'] ) ) {
            $link .= ' (' . number_format_i18n( $category->count ) . ')';
        }
}

の部分をカットして、

$link .= $cat_name;

$link .= '</a>';

の間にコピー(移動)します。
次に、wp_list_categoriesを呼び出す時に、下記のようにnewでWalker_Category_Linkin_Postcountインスタンスを作成してwalker オプションに指定します。

<h2>カテゴリ</h2>
<ul>
<?php wp_list_categories(array("title_li" => '',
                         'show_count' => 1,
                         'walker' => new Walker_Category_Linkin_Postcount()));
?>
</ul>

これでめでたく、記事数が a タグの中に入りました。

memo20160715b

クラスの全体は下記のようになります。

class Walker_Category_Linkin_Postcount extends Walker_Category {
    public function start_el( &$output, $category, $depth = 0, $args = array(), $id = 0 ) {
        /** This filter is documented in wp-includes/category-template.php */
        $cat_name = apply_filters(
            'list_cats',
            esc_attr( $category->name ),
            $category
        );

        // Don't generate an element if the category name is empty.
        if ( ! $cat_name ) {
            return;
        }

        $link = '<a href="' . esc_url( get_term_link( $category ) ) . '" ';
        if ( $args['use_desc_for_title'] && ! empty( $category->description ) ) {
            /**
             * Filter the category description for display.
             *
             * @since 1.2.0
             *
             * @param string $description Category description.
             * @param object $category    Category object.
             */
            $link .= 'title="' . esc_attr( strip_tags( apply_filters( 'category_description', $category->description, $category ) ) ) . '"';
        }

        $link .= '>';
        $link .= $cat_name;

        if ( ! empty( $args['show_count'] ) ) {
            $link .= ' (' . number_format_i18n( $category->count ) . ')';
        }

        $link .= '</a>';

        if ( ! empty( $args['feed_image'] ) || ! empty( $args['feed'] ) ) {
            $link .= ' ';

            if ( empty( $args['feed_image'] ) ) {
                $link .= '(';
            }

            $link .= '<a href="' . esc_url( get_term_feed_link( $category->term_id, $category->taxonomy, $args['feed_type'] ) ) . '"';

            if ( empty( $args['feed'] ) ) {
                $alt = ' alt="' . sprintf(__( 'Feed for all posts filed under %s' ), $cat_name ) . '"';
            } else {
                $alt = ' alt="' . $args['feed'] . '"';
                $name = $args['feed'];
                $link .= empty( $args['title'] ) ? '' : $args['title'];
            }

            $link .= '>';

            if ( empty( $args['feed_image'] ) ) {
                $link .= $name;
            } else {
                $link .= "<img src='" . $args['feed_image'] . "'$alt" . ' />';
            }
            $link .= '</a>';

            if ( empty( $args['feed_image'] ) ) {
                $link .= ')';
            }
        }


        if ( 'list' == $args['style'] ) {
            $output .= "\t<li";
            $css_classes = array(
                'cat-item',
                'cat-item-' . $category->term_id,
            );

            if ( ! empty( $args['current_category'] ) ) {
                $_current_category = get_term( $args['current_category'], $category->taxonomy );
                if ( $category->term_id == $args['current_category'] ) {
                    $css_classes[] = 'current-cat';
                } elseif ( $category->term_id == $_current_category->parent ) {
                    $css_classes[] = 'current-cat-parent';
                }
            }

            /**
             * Filter the list of CSS classes to include with each category in the list.
             *
             * @since 4.2.0
             *
             * @see wp_list_categories()
             *
             * @param array  $css_classes An array of CSS classes to be applied to each list item.
             * @param object $category    Category data object.
             * @param int    $depth       Depth of page, used for padding.
             * @param array  $args        An array of wp_list_categories() arguments.
             */
            $css_classes = implode( ' ', apply_filters( 'category_css_class', $css_classes, $category, $depth, $args ) );

            $output .=  ' class="' . $css_classes . '"';
            $output .= ">$link\n";
        } else {
            $output .= "\t$link<br />\n";
        }
    }
}

他の表示系のカスタマイズもこのクラスを修正する事ができそうです。