Ask your WordPress questions! Pay money and get answers fast! Comodo Trusted Site Seal
Official PayPal Seal

How to return just the parents using get_the_terms? WordPress

  • SOLVED

I have a custom post type using a hierarchical custom taxonomy. For the selected post I want to list out all the parent terms that have been applied to it. No child terms, just the parents.

Answers (4)

2016-11-07

Arnav Joy answers:

please check this.


<?php

$terms = get_the_terms( $post, $taxonomy );

if( $terms ){
foreach( $terms as $term ){
if( $term->parent == 0 )
$term_arr[$term->term_id] = $term->name;
}

if( $term_arr ){
print_r($term_arr);
}
}


Arnav Joy comments:

you have to change $taxonomy to the desired custom tax name..


hft563 comments:

This works, but it returns 'Array ([1092]=>' as well as the term name. How can I strip that stuff out so I'm listing just the name?


hft563 comments:

NM. I used implode and it worked. Thanks.

2016-11-07

Reigel Gallarde answers:

have you tried something like this?

$myterms = get_terms( array( 'taxonomy' => 'taxonomy_name', 'parent' => 0 ) );

2016-11-07

Rempty answers:

You can create your own function, add this code to functions.php

function get_parent_terms($postid=null,$taxonomy){
if ($postid === null)
return false;
$terms=wp_get_post_terms($postid,$taxonomy);
if($terms){
foreach ( $terms as $term ) {
if($term->parent=='0')
$termr[]=$term;
}
return $termr;
}
return false;
}

And you can use it like:
$taxonomy='custom-taxonomy-name';
$postid=$post->ID;
$terms=get_parent_terms($postid,$taxonomy);
foreach($terms as $term){
echo $term->name.'<br>';
}

2016-11-07

Kyle answers:

Instead of writing your own replacement function, get_the_terms also has its own filter built into it by the same name, so if you use this instead, it will get the result



add_filter( 'get_the_terms', 'parents_only' );
function parents_only ( $terms, $post_id, $taxonomy ){

if( $post_id != '123'){ //change 123to your post ID
return $terms;
}

foreach( $terms as $key => $term ){

if( $term->parent) ){ //If a parent exists, remove it from the term array, parents only!
unset( $terms[$key] );
}


return $terms;

}