2015-04-16 26 views
0

我有一個自定義帖子類型的循環,所有工作都很好,除非我無法返回該帖子分配給它的實際類別名稱。在Wordpress中返回一個類別的名稱

我有以下代碼:

<?php 
    $posts = get_posts(array(
    'numberposts' => -1, 
    'post_type' => 'portfolio', 
    'orderby' => 'menu_order', 
    'order' => 'ASC' 
)); 


    if($posts) { 
    foreach($posts as $post) { 
     setup_postdata($post); 
     ?> 
     <div> 
     <div class="mix <?php get_cat_name(); ?>" ><img src="<?php the_field('portfolio_image'); ?>" alt=""></div> <!-- ACF --> 
     </div> 
     <?php 
    } 
    } 
    wp_reset_postdata(); 
?> 

這只是我曾嘗試包括回聲特林所有WP食品功能之一。我想我的問題是別的嗎? 非常感謝提前。

回答

2

根據codex的id是要求這個方法(https://codex.wordpress.org/Function_Reference/get_cat_name)。退出ID不起作用。

一個解決方案是使用get_the_category($postId)來檢索您的帖子的類別(https://codex.wordpress.org/Function_Reference/get_the_category)。你可以離開了這裏的帖子ID

POST_ID (整數)(可選)的帖子ID。 默認值:$ post-> ID(當前帖子ID)

請注意,該方法返回一個對象 - 而不是類別名稱。你可以試試下面的代碼,看看它的工作:

<?php 
$category = get_the_category(); 
echo $category[0]->cat_name; 
?> 
+0

謝謝,但第二個選項只是沒有返回 –

+0

@PeteNorris:我添加了一個例子。 – Fred

+0

GEEEENIUS!謝謝 –

0

試試這個代碼

 <?php $terms = get_the_terms($post->ID, 'TAXONOMY'); 
    if ($terms && ! is_wp_error($terms)) : 
    $term_slugs_arr = array(); 
     foreach ($terms as $term) { 
     $term_slugs_arr[] = $term->name; 
    } 
    $terms_slug_str = join(" ", $term_slugs_arr); 
    endif; 
    echo $terms_slug_str;?> 
+0

謝謝。我把它放在最初的循環中(不知道這是否是正確的地方),沒有任何東西被返回。 –

0

替換代碼

get_cat_name();

$categories = get_the_terms($post->ID,'custom-texonomy-name');     
$cat = key($categories); 
echo $categories[$cat]->name; 
+0

其中取代自定義文件名稱與您的註冊文本名稱 –

+0

請嘗試更新的代碼..現在應該工作... –

相關問題