wordpress 使用get_the_category 和get_term_link 獲取文章分類 最簡單的辦法



閱讀原文獲取更佳體驗
php


在wordpress 中。獲取文章分類的辦法有不少。數組

最多見的是下面這個代碼段ide

function custom_taxonomies_terms_links(){
    //根據當前文章ID獲取文章信息
    $post = get_post( $post->ID );
 
    //獲取當前文章的文章類型
    $post_type = $post->post_type;
 
    //獲取文章所在的自定義分類法
    $taxonomies = get_object_taxonomies( $post_type, 'objects' );
 
    $out = array();
    foreach ( $taxonomies as $taxonomy_slug => $taxonomy ){
        $term_list = wp_get_post_terms($post->ID, $taxonomy_slug, array("fields" => "all"));
        echo $term_list[0]->name; //顯示文章所處的分類中的第一個
    }
 
    return implode('', $out );
}


但後面通過本身從新編寫。更加簡短,更加符合本身的要求wordpress

代碼以下函數

/**
 *獲取分類
 **/
function deel_category(){
  $tag_arr = get_the_category();
  foreach($tag_arr as $value){
    if(!empty($value)){
      echo '<a data-bear="main" href='.get_term_link($value->slug,$value->taxonomy).'>'.$value->name.'<a>';
    }
  }
}


把這段代碼放到functions.php 中去。而後在須要顯示分類的位置插上 <?php deel_category();?>。post

 

get_the_category()   返回當前文章所屬分類的數組集合spa

用法:blog

參數:$id 文章id,默認是當前文章ID,類型爲整數,可選get

返回的值:數組博客

數組的格式以下圖所示


wKioL1Y4MYSiL5pfAAGSQeQjlDA564.jpg


其中咱們最須要用到的固然就是name 啦

但當你須要給 name分類  添加 a 標籤時,這時須要一個wp函數來獲取分類的地址

函數get_term_link 是用來獲取分類地址的

使用方式

<?php get_term_link( $term, $taxonomy ); ?>

咱們將get_the_category返回的數組中的slug  和 taxonomy 字段傳入到這個函數,便可獲取到分類對應的地址了

相關文章
相關標籤/搜索