terms - Get taxonomy name of current post

admin2025-04-19  0

Hierarchical taxonomy of custom post type 'projects' > 'projects_category'.

Two example 'projects_category' hierarchies would be:

Big Corporates > 1st Company Name > A Post Title

Small Business > 2nd Company Name > Another Post Title

I can get '1st Company Name' with the following:

<?php $terms = get_the_terms($post->ID, 'projects_category');foreach($terms as $term){echo $term->name;} ?>

How can I display 'Big Corporates' or 'Small Business' as appropriate in single.php ?

Hierarchical taxonomy of custom post type 'projects' > 'projects_category'.

Two example 'projects_category' hierarchies would be:

Big Corporates > 1st Company Name > A Post Title

Small Business > 2nd Company Name > Another Post Title

I can get '1st Company Name' with the following:

<?php $terms = get_the_terms($post->ID, 'projects_category');foreach($terms as $term){echo $term->name;} ?>

How can I display 'Big Corporates' or 'Small Business' as appropriate in single.php ?

Share Improve this question edited Nov 15, 2019 at 12:32 butlerblog 5,1213 gold badges28 silver badges44 bronze badges asked Jul 13, 2011 at 7:16 AndyAndy 2251 gold badge5 silver badges13 bronze badges
Add a comment  | 

4 Answers 4

Reset to default 5

get_ancestors() should do what you need:

So, you should do something like this:

$ancestors = get_ancestors($term_id, 'projects_category)

If you read this article on custom post types it should help: Revisiting Custom Post Types, Custom Taxonomies, and Permalinks

I've marked up anu's answer and get_ancestors explanation, however this is how I solved it:

<?php 
$terms = wp_get_object_terms($post->ID, 'projects_category', array('orderby' => 'term_id', 'order' => 'ASC') );
    if ( !empty( $terms ) ) :
    $project = array();
    foreach ( $terms as $term ) {
        $project[] = $term->name;
}
    echo '<h1>'.$project[0].'</h1>';
    echo '<h2>'.$project[1].'</h2>';
    endif;
    ?>

This is very good code for get taxonomy title in detail page or single page in custom post type in WordPress,

<?php $terms = get_the_terms($post->ID, 'projects_category');foreach($terms as $term){echo $term->name;} ?>
转载请注明原文地址:http://conceptsofalgorithm.com/Algorithm/1745001831a279275.html

最新回复(0)