子比主题美化 分类添加数量显示

Jaysun

d2b5ca33bd20240606052451.png

之前网站分享过分类角标的显示,今天分享一个分类文章数量的显示,喜欢的自行测试。

使用教程

在你的 functions.php 文件中,添加以下代码,定义一个自定义 Walker 类,用于处理分类项目并在其后面显示文章数量。

class Custom_Walker_Nav_Menu extends Walker_Nav_Menu {
    // 开始输出每个菜单项
    function start_el(&$output, $item, $depth = 0, $args = array(), $id = 0) {
        // 和默认 Walker 一样处理元素的基础部分
        $classes = empty($item->classes) ? array() : (array) $item->classes;
        $class_names = join(' ', apply_filters('nav_menu_CSS_class', array_filter($classes), $item));
        $class_names = $class_names ? ' class="' . esc_attr($class_names) . '"' : '';

        $id = apply_filters('nav_menu_item_id', 'menu-item-'. $item->ID, $item);
        $id = $id ? ' id="' . esc_attr($id) . '"' : '';

        $output .= '<li' . $id . $class_names .'>';

        $atts = array();
        $atts['title']  = ! empty( $item->attr_title ) ? $item->attr_title : '';
        $atts['target'] = ! empty( $item->target )     ? $item->target     : '';
        $atts['rel']    = ! empty( $item->xfn )        ? $item->xfn        : '';
        $atts['href']   = ! empty( $item->url )        ? $item->url        : '';

        $atts = apply_filters('nav_menu_link_attributes', $atts, $item, $args);

        $attributes = '';
        foreach ( $atts as $attr => $value ) {
            if ( ! empty( $value ) ) {
                $value = ( 'href' === $attr ) ? esc_url( $value ) : esc_attr( $value );
                $attributes .= ' ' . $attr . '="' . $value . '"';
            }
        }

        $item_output = $args->before;
        $item_output .= '<a'. $attributes .'>';
        $item_output .= $args->link_before . apply_filters('the_title', $item->title, $item->ID) . $args->link_after;

        // 添加分类项的文章数量
        if ($item->object == 'category') {
            $category_id = $item->object_id;
            $category = get_category($category_id);
            if ($category) {
                $count = $category->count;
                $item_output .= ' (' . $count . ')';
            }
        }

        $item_output .= '</a>';
        $item_output .= $args->after;

        $output .= apply_filters('walker_nav_menu_start_el', $item_output, $item, $depth, $args);
    }
}

在你的 zib_menu_items 函数中,使用自定义 Walker 类来生成导航菜单:

函数位于/inc/functions/zib-header.php 搜索zib_menu_items($location = 'topmenu', $echo = true)

将整个函数替换为

VIP专属内容
白银VIP 免费查看
开通会员
开通白银VIP可查看该内容
该内容VIP会员可见,您未登录,请先登录

您需要 登录账户 后才能发表评论

发表评论

快捷回复: 表情:
AddoilApplauseBadlaughBombCoffeeFabulousFacepalmFecesFrownHeyhaInsidiousKeepFightingNoProbPigHeadShockedSinistersmileSlapSocialSweatTolaughWatermelonWittyWowYeahYellowdog
验证码
评论列表 (暂无评论,542人围观)

还没有评论,来说两句吧...

目录[+]

取消
微信二维码
微信二维码
支付宝二维码