2015-07-21 154 views
0

我正在嘗試獲取自定義帖子類型循環中單個帖子的類別的未格式化列表(最好是一個slug)。這個列表最終將作爲一個div的類($CATEGORYSLUGSWILLEVENTUALLYGOHERE)。在自定義帖子類型中獲取單個帖子的類別

我發現了幾種不同的方法來獲取一個自定義帖子類型的所有類別的列表,但不是一個特定的單個類別的列表。這是我到目前爲止有:

<?php $projects_loop = new WP_Query(array('post_type' => 'projects', 'orderby' => 'menu_order')); ?> 

         <?php while ($projects_loop->have_posts()) : $projects_loop->the_post(); ?> 


          <div class="box <?php $CATEGORYSLUGSWILLEVENTUALLYGOHERE; ?>"> 

            <div class="port-item-home"> 
             <a href="<?php the_permalink(); ?>"><?php the_post_thumbnail('portfolio-home'); ?></a> 
             <p><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></p> 
            </div> 

           </div> 



        <?php endwhile; ?> 

而且這裏是我到目前爲止已經試過讓類別列表:

<?php 
            $args = array(
             'orderby' => 'name', 
             'parent' => 0, 
             'taxonomy' => 'project-type' 
            ); 
            $categories = get_categories($args); 

            echo '<p> '.print_r(array_values($categories)).'something</p>' 

           ?> 

我有它返回數組 - 但陣列表明這將顯示所有類別,而不是與特定帖子有關的類別。

我也試過:

<?php 
    //list terms in a given taxonomy (useful as a widget for twentyten) 
     $taxonomy = 'project-type'; 
     $tax_terms = get_terms($taxonomy); 
?> 

<?php 
    foreach ($tax_terms as $tax_term) { 
     echo $tax_term->name; 
    } 
?> 

而這也顯示所有類別,而不是有關職位的人。

有什麼建議?

回答

1

Got it!發現這篇文章,幫助我了:

https://wordpress.org/support/topic/how-to-get-the-category-name-for-a-custom-post-type

<!-- The Query --> 
<?php 
    $args = array( 
     'post_type'  => 'my_post_type', 
     'posts_per_page' => -1, 
     'orderby'  => 'menu_order'); 

    $custom_query = new WP_Query($args); 
?> 

<!-- The Loop --> 
<?php 
    while ($custom_query->have_posts()) : 
     $custom_query->the_post(); 
     $terms_slugs_string = ''; 
     $terms = get_the_terms($post->ID, 'my_post_type'); 
     if ($terms && ! is_wp_error($terms)) {     
      $term_slugs_array = array(); 
      foreach ($terms as $term) { 
       $term_slugs_array[] = $term->slug; 
      } 
      $terms_slugs_string = join(" ", $term_slugs_array); 
     } 
?> 

    <div class="box<?php echo $terms_slugs_string ?>">   
     <div class="port-item-home"> 
      <a href="<?php the_permalink(); ?>"> 
       <?php the_post_thumbnail('portfolio-home'); ?> 
      </a> 
      <a href="<?php the_permalink(); ?>"> 
       <?php the_title(); ?> 
      </a> 
     </div> 
    </div> 

<?php endwhile; ?> 
相關問題