douzhi2012 2018-06-19 12:13
浏览 37
已采纳

Wordpress类别:如何在单个帖子中显示名称,slug,描述和链接?

What I want to do is, within single.php, pull different properties of the Category separately, like this:

<?php if ( have_posts() ) : ?>
    <?php while ( have_posts() ) : the_post(); ?>

        <a class="CATEGORYSLUG" href="CATEGORYLINK">
            <i class="fas CATEGORYDESCRIPTION"></i>
            <span>CATEGORYNAME</span>
        </a>

    <?php endwhile; ?>
<?php endif; ?>

To produce an end product like this:

enter image description here

So that I can use:

  1. the category slug as a CSS class, to style each category a unique color
  2. the category description as a Font Awesome class (in this case, "fa-wrench"), to assign each category a unique icon

(For this project, each post will only be assigned a single category, but I suppose a future-proof solution would need to output ALL categories assigned to the post in this format.)

So I really just need to know how to individually pull:

  1. Category slug
  2. Category link
  3. Category description
  4. Category name
  • 写回答

2条回答 默认 最新

  • douche1936 2018-06-19 12:37
    关注

    You can use the get_the_terms() function to get all of the categories assigned to that post object and loop through each one to create your icons etc.

    Below is an example, I've called each individual variable so that you can see the object properties clearly.

    This will also work if you only have one category assigned.

    //get all categories:
    $categories = get_the_terms(get_the_ID(), 'category');
    
    //loop through categories
    foreach ($categories as $category) {
        //get variables
        $slug   = $category->slug;
        $link   = get_term_link($category->term_id);
        $descr  = $category->description;
        $name   = $category->name;
    
        //echo your content
        echo '<a class="'.$slug.'" href="'.$link.'"><i class="fas '.$descr.'"></i><span>'.$name.'</span></a>';
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 在获取boss直聘的聊天的时候只能获取到前40条聊天数据
  • ¥20 关于URL获取的参数,无法执行二选一查询
  • ¥15 液位控制,当液位超过高限时常开触点59闭合,直到液位低于低限时,断开
  • ¥15 marlin编译错误,如何解决?
  • ¥15 有偿四位数,节约算法和扫描算法
  • ¥15 VUE项目怎么运行,系统打不开
  • ¥50 pointpillars等目标检测算法怎么融合注意力机制
  • ¥20 Vs code Mac系统 PHP Debug调试环境配置
  • ¥60 大一项目课,微信小程序
  • ¥15 求视频摘要youtube和ovp数据集