2013-06-25 156 views
5

是否有可能獲得給定帖子ID的類別的類別名稱,以下代碼用於獲取類別標識,但如何獲取名稱?從帖子ID獲取類別名稱

<?php $post_categories = wp_get_post_categories(4); echo $post_categories[0]?> 

謝謝!

回答

16

在這裏你去get_the_category($post->ID);將通過陣列

$category_detail=get_the_category('4');//$post->ID 
foreach($category_detail as $cd){ 
echo $cd->cat_name; 
} 

get_the_category

+0

謝謝,但我在哪裏定義該代碼中的職位ID,我想要的類別名稱。 – user1937021

+0

看到我編輯的答案 –

+0

我不喜歡你如何迭代數組來獲取名稱,但它的工作原理。 – Radmation

0

使用get_the_category()函數。

$post_categories = wp_get_post_categories(4); 
$categories = get_the_category($post_categories[0]); 
var_dump($categories); 
+0

很酷,但我該如何迴應結果? – user1937021

+0

@ user1937021你檢查過輸出嗎? – swapnesh

+0

是@swapnesh輸出給我這個數組(0){} – user1937021

5

返回崗位的類別,你需要循環的數組不

<?php get_the_category($id) ?> 

做只是,在循環內?

對於外:

<?php 
global $post; 
$categories = get_the_category($post->ID); 
var_dump($categories); 
?> 
+0

爲我返回一個數組 - 不是類別的名稱 – Radmation

1
function wp_get_post_categories($post_id = 0, $args = array()) 
{ 
    $post_id = (int) $post_id; 
    $defaults = array('fields' => 'ids'); 
    $args = wp_parse_args($args, $defaults); 
    $cats = wp_get_object_terms($post_id, 'category', $args); 

    return $cats; 
} 

這裏是功能wp_get_post_categories() 第二個參數,其可以傳遞接收數據的屬性。

$category_detail = get_the_category('4',array('fields' => 'names')); //$post->ID 
foreach($category_detail as $cd) 
{ 
    echo $cd->name; 
} 
8
echo '<p>'. get_the_category($id)[0]->name .'</p>'; 

是什麼,你也許尋找。

+0

謝謝!正是我所需要的 - 沒有循環 - 更漂亮 – Radmation

+0

謝謝...它返回的帖子類別名稱我們是 – TusharG

+0

這是非常好的,如果不需要使用循環,例如。在單個帖子模板中。尼斯。 – Marek

0
 <?php 
    // in woocommerce.php 
    $cat = get_queried_object(); 
    $cat->term_id; 
    $cat->name; 
    ?> 

    <?php 
    // get product cat image 
     if (is_product_category()){ 
      $cat = get_queried_object(); 
      $thumbnail_id = get_woocommerce_term_meta($cat->term_id, 'thumbnail_id', true); 
      $image = wp_get_attachment_url($thumbnail_id); 
      if ($image) { 
       echo '<img src="' . $image . '" alt="" />'; 
      }  
} 
?> 
相關問題