2017-05-07 43 views
1

我用下面的代碼獲取分類毛坯:擷取分類彈頭

<?php 
    $terms = get_the_terms($post->ID, 'locations'); 
    if (!empty($terms)){ 
     $term = array_shift($terms); 
    } 
?> 

然後我用下面的代碼輸出毛坯:

<?php echo $term->slug; ?> 

我的問題是,我怎麼能使用它在相同的位置輸出兩種不同的分類法?例如:

<?php 
    $terms = get_the_terms($post->ID, 'locations', 'status'); 
    if (!empty($terms)){ 
     $term = array_shift($terms); 
    } 
?> 

我想我可以添加術語'位置','狀態',但它不起作用。

回答

0

如果你想顯示兩個或更多的分類標準,那麼我認爲你應該循環$ terms變量。

<?php 
    $terms = get_the_terms($post->ID, 'locations'); 
    if (!empty($terms)){ 
     foreach ($terms as $term): 
      echo $term->slug; 
     endforeach; 
    } 
?> 

希望它能幫助你。

謝謝

+0

感謝評論。我已經更新了我的答案,使其更清晰。我正嘗試使用上面的代碼輸出兩個不同的分類法。 – CharlyAnderson

+0

它真的取決於你想輸出什麼? –

+0

我想輸出分類學slu。。 – CharlyAnderson

0

據爲get_the_terms官方文檔中,只有一個分類法可以提供。如果你想輸出兩個不同分類法中所有術語的slu,,你可以按穆罕默德的建議做,但是兩次。

<?php 

// output all slugs for the locations taxonomy 
$locations_terms = get_the_terms($post->ID, 'locations'); 
if (! empty($locations_terms)) { 
    foreach ($locations_terms as $term) { 
     echo $term->slug; 
    } 
} 

// output all slugs for the status taxonomy 
$status_terms = get_the_terms($post->ID, 'status'); 
if (! empty($status_terms)) { 
    foreach ($status_terms as $term) { 
     echo $term->slug; 
    } 
} 
?> 

不過,如果你只在乎得到各分類的單個詞的蛞蝓,你可能會發現get_term_by更加有用。

<?php 
$loc_field = 'name'; 
$loc_field_value = 'special location'; 
$loc_taxonomy = 'locations'; 
$locations_term = get_term_by($loc_field, $loc_field_value, $loc_taxonomy); 
echo $locations_term->slug; 

$stat_field = 'name'; 
$stat_field_value = 'special status'; 
$stat_taxonomy = 'status'; 
$status_term = get_term_by($stat_field, $stat_field_value, $stat_taxonomy); 
echo $status_term->slug; 
?>