获取当前帖子的帖子术语(选定的分类术语)-如何只获取分类值,而不是前端的“数组([0]=>分类术语)”?

时间:2017-11-05 作者:Moe

我使用来自的get\\u post\\u术语代码https://codex.wordpress.org/Function_Reference/wp_get_post_terms. 我可以从当前帖子中检索选定的分类术语,但显示的值如下所示:数组([0]=>分类术语)。我只想把分类术语放在前端。

//Returns Array of Term Names for "my_taxonomy" $term_list = wp_get_post_terms($post->ID, \'my_taxonomy\', array("fields" => "names")); print_r($term_list);

有人知道如何只显示选定的分类术语吗?

3 个回复
SO网友:omukiguy

假设分类名称为“动物”

<?php
    //This will show all the terms in taxonomy whether they have posts or not thus the "hide_empty"
    $terms = get_terms( array ( \'taxonomy\' => \'animals\', \'hide_empty\' => false, \'parent\' => 0, \'orderby\' => \'description\', \'order\' => \'ASC\' ));

    foreach ($terms as $term) {
        // The $term is an object, so we can get the names.
        //use var_dump($term) to see other options available
        echo $name = $term->name;
    }
?>

SO网友:jaswrks

这个wp_get_post_terms() function 使用调用时返回一个或多个术语名称array( \'fields\' => \'names\' ). 所以你有几个不同的选择。

抓取找到的第一个术语名称。

<?php
$term_names = wp_get_post_terms($post->ID, \'my_taxonomy\', array(\'fields\' => \'names\'));

if ( ! empty( $term_names ) ) {
  echo $term_names[0]; // Cats
}
或者,您可以内爆术语名称列表,并以逗号分隔的格式显示它们。

<?php
$term_names = wp_get_post_terms($post->ID, \'my_taxonomy\', array(\'fields\' => \'names\'));

echo implode(\', \', $term_names); // Cats, Pets, Animals
或者,您可以遍历列表并执行其他操作。

<?php
$term_names = wp_get_post_terms($post->ID, \'my_taxonomy\', array(\'fields\' => \'names\'));

foreach( $term_names as $name ) {
    echo $name.\'<br />\';
}

SO网友:Moe

它与此代码一起工作,只显示名称,但是输出以小字符显示,因此我只需要以某种方式将其大写

<?php // Get terms for post $terms = get_the_terms( $post->ID , \'my_taxonomy\' ); // Loop over each item since it\'s an array if ( $terms != null ){ foreach( $terms as $term ) { // Print the name method from $term which is an OBJECT print $term->slug ; // Get rid of the other data stored in the object, since it\'s not needed unset($term); } } ?>

结束

相关推荐

Taxonomy Page Go to 404 pgae

我正在使用Redux框架创建一个自定义帖子类型。创建一个类别和该类别视图直接和直接转到链接,但该链接应直接转到404页。请检查下面的代码,让我知道我的代码中有什么错误。remove_action( \'init\', \'brightness_service_register\',10 ); add_action( \'init\', \'brightness_service_register\',1 ); function brightness_service_register()