Get terms with a parent

With the following function you can return only the terms with a parent term (so are child terms), by post id and taxonomy. Notice that there terms also can be parents when using multiple levels of hierarchy.

/**
 * Returns terms with parents of a post
 *
 * @param int $post_id the post
 * @param mixed $taxonomy to get terms from specific taxonomy
 */
function get_terms_with_parent( $post_id, $taxonomy ) {
    if ( empty( $post_id ) ) {
        global $post;
        $post_id = $post->ID;
    }
    $terms = wp_get_post_terms( $post_id, $taxonomy );
    foreach ( $terms as $key => $term ) {
        if ( $term->parent != 0 ) {
            $new_terms[] = $term;
        }
    }
    return $new_terms;
}
Robbert Vermeulen

Need help from a WordPress expert?

I would love to hear about your project and how I can help you achieve your goals