-1

I have a custom post type and a taxonomy, when adding a post if I select a child term and not the parent term then I cannot use get terms as the parent term wont be in the array as it wasn't selected so I was wondering if it possible to get the parent term/id using a child term?

As I was to do an if statement so that if a single post parent term is (id 4) then display something.

So I need to get terms (all of which will be a child term and using the child term get the parent term for that term)

  • This question with answers can probably help you get going... wordpress.stackexchange.com/questions/24794/… – Sean Grant Mar 12 '15 at 14:34
  • Thanks for the link however that example means the user has selected the top level parent they wish to display where as I want to display the top level parent based on if the child term which is selected. – user3660898 Mar 12 '15 at 14:37
  • You're right, it's not the exact solution you are looking for as it goes all the way to the top level parent. That's why I said it could get you going... in the right direction. – Sean Grant Mar 12 '15 at 15:16
3

Inside the loop you can make use of wp_get_post_terms() to return all the terms associated with the specific post. This object returned holds all the terms with all the properties of the specified terms

With that in mind, you can use a foreach loop to get each term, and then check each term's parent. For grandchild terms you will need to do some extra checking here to determine the parent or top most level term parent

You can do something like this

$terms = wp_get_post_terms( $post->ID, 'category' );
if ( !empty( $terms ) && !is_wp_error( $terms ) ){
    foreach ( $terms as $term ) {
        if ( $term->parent == 4 ) {
            //Do something if parent is 4
        }
    }
}

EDIT

To make this work with deeper level categories, you can use get_ancestors() to get all levels and use in_array() to test for the specific category ID

You can extend the function as follow:

$terms = wp_get_post_terms( $post->ID, 'category' );
if ( !empty( $terms ) && !is_wp_error( $terms ) ){
    foreach ( $terms as $term ) {
        if( $term->parent != 4 && $term->parent == 0 )
            continue;

        if ( $term->parent == 4 || in_array( 4, get_ancestors( $term->term_id, 'category' ) )) {
            //Do something if parent ID is 4
        } else {
            //Do nothing
        }
    }
}
  • Thanks, now I just need to find out how i can extend it so that if the category is more than 1 depth – user3660898 Mar 12 '15 at 15:01
  • See my update, should work in theory :-) – Pieter Goosen Mar 12 '15 at 17:24

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.