2017-05-07 45 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; 
?>