标签: the_category

  • wordpress自定the_category的输出结构

    通过WordPress的过滤器the_category来自定义输出内容。方法很简单,但是很实用。以下是一个示例代码:

    function custom_the_category($thelist, $separator = '', $parents = '') {
        // 获取当前文章的所有分类
        $categories = get_the_category();
    
        if (empty($categories)) {
            return $thelist;
        }
    
        $thelist = '';
        foreach ($categories as $category) {
            $cat_name = esc_html($category->name);
            $cat_link = esc_url(get_category_link($category->term_id));
    
            // 自定义每个分类的HTML结构
            $thelist .= '<div class="custom-category-item">';
            $thelist .= '<a href="' . $cat_link . '" class="custom-category-link">';
            $thelist .= '<span class="custom-category-name">' . $cat_name . '</span>';
            $thelist .= '</a>';
            $thelist .= '</div>';
        }
    
        return $thelist;
    }
    add_filter('the_category', 'custom_the_category', 10, 3);

    然后在模板文件中,你可以像平常一样调用the_category()函数:

    <?php the_category(', '); ?>
  • WordPress the_category与single_cat_title

    在wordpress网站主题开发用常会用到调用分类目录的名称,the_category与single_cat_title都可以调用出分类目录的名称。

    <?php single_cat_title(); ?>
    <?php the_category(); ?>
    

    但是,不少人搞不清楚二者有什么区别,其实很简单。

    如果用single_cat_title调用分类名称,在分类里没文章时可以显示分类名称。用the_category分类名称,在分别里没文章时不会显示分类名称。

    就这么点区别,其它的没什么区别。