How to get the parent terms of any taxonomy

A post may have many taxonomies and each taxonomy may have also many terms and then each term may have many sub-terms.

What happens when you want to display a list of your terms with the links? And also, if showing all of them may be too much. A better choice will be to display only the parent terms. That’s cool, but WP does not contain a function for this.

So here we go:


function zerowp_get_parent_terms($taxonomy = 'category')
{
    $currentPost = get_post();
    $terms       = get_the_terms($currentPost->ID, $taxonomy);

    if (is_wp_error($terms)) {
        /** @var \WP_Error $terms */
        throw new \Exception($terms->get_error_message());
    }

    $map = array_map(
        function ($term) use ($taxonomy) {
            return '<a href="' . esc_url(get_term_link($term->term_id,
                    $taxonomy)) . '" title="' . esc_attr($term->name) . '">
                ' . $term->name . '
                </a>';
        },
        array_filter($terms, function ($term) {
            return $term->parent == 0;
        })
    );

    return implode(', ', $map);
}

Example usage:

This function can be called on the single post page.

Get the default categories for built-in post type:

echo zerowp_get_parent_terms(); // The default value on first arg is 'category', so we can ignore it.

Get the default tags for built-in post type:

echo zerowp_get_parent_terms('post_tag');

Get a custom taxonomy:

echo zerowp_get_parent_terms('my_custom_tax_name');
Member since January 2, 2019

As a seasoned WordPress developer with expertise in various tech stacks and languages, I bring years of experience to every project I handle. My passion for coding and dedication to delivering exceptional work ensures that each project I take on is of the highest quality. I specialize in creating custom themes, developing plugins, and building full-scale web systems. By staying up-to-date with the latest industry trends and best practices, I incorporate cutting-edge solutions into my work.

Comments

    Your email address will not be published. Required fields are marked *