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 metadata提取的PDF元数据,如何转换为一个Excel
  • ¥15 关于arduino编程toCharArray()函数的使用
  • ¥100 vc++混合CEF采用CLR方式编译报错
  • ¥15 coze 的插件输入飞书多维表格 app_token 后一直显示错误,如何解决?
  • ¥15 vite+vue3+plyr播放本地public文件夹下视频无法加载
  • ¥15 c#逐行读取txt文本,但是每一行里面数据之间空格数量不同
  • ¥50 如何openEuler 22.03上安装配置drbd
  • ¥20 ING91680C BLE5.3 芯片怎么实现串口收发数据
  • ¥15 无线连接树莓派,无法执行update,如何解决?(相关搜索:软件下载)
  • ¥15 Windows11, backspace, enter, space键失灵