get_ancestors

Home » Functions » get_ancestors

Function Name: get_ancestors

Explanation: The get_ancestors function is a useful WordPress function that retrieves the ancestors of a given object within a hierarchical taxonomy, such as categories or custom taxonomies. It returns an array of IDs of the ancestor terms, ordered from the closest ancestor to the farthest.

This function is particularly handy when you want to display a hierarchical breadcrumb trail, showing the path from a specific term to its top-level parent. It allows you to easily retrieve and manipulate the ancestor terms in a hierarchical taxonomy structure.

The get_ancestors function takes three parameters: the first parameter is the ID of the object whose ancestors you want to retrieve, the second parameter is the taxonomy of the object (e.g., category or custom taxonomy), and the third parameter is the output type (either ‘array’ or ‘string’).

Example Usage: Let’s say you have a hierarchical category structure in your WordPress site, and you want to display a breadcrumb trail for a specific category, showing its path up to the top-level category. You can use the get_ancestors function to retrieve the ancestor category IDs and then display them in the desired format.

Here’s an example code snippet that demonstrates the usage of the get_ancestors function:

$category_id = 123; // ID of the specific category
$taxonomy = 'category'; // Taxonomy of the object

$ancestors = get_ancestors($category_id, $taxonomy, 'array');

if (!empty($ancestors)) {
    $breadcrumb = '';
    foreach ($ancestors as $ancestor_id) {
        $ancestor = get_category($ancestor_id);
        $breadcrumb .= '<a href="' . get_category_link($ancestor_id) . '">' . $ancestor->name . '</a> > ';
    }

    echo rtrim($breadcrumb, ' > '); // Display the breadcrumb trail, removing the trailing '>'
} else {
    echo 'No ancestors found.';
}

In this example, we first specify the ID of the category we want to retrieve the ancestors for ($category_id) and the taxonomy it belongs to ($taxonomy). We then call the get_ancestors function, passing in these parameters and specifying the output type as an array.

If the function returns an array of ancestor category IDs, we can iterate through them using a foreach loop. Inside the loop, we retrieve each ancestor category object using the get_category function and construct the breadcrumb trail by appending the ancestor’s name and link. Finally, we display the breadcrumb trail by echoing the $breadcrumb variable.

If the get_ancestors function returns an empty array, it means that the category has no ancestors, and we display the corresponding message.

The get_ancestors function is a powerful tool for navigating hierarchical taxonomies in WordPress, enabling you to build breadcrumb trails or perform other hierarchical operations efficiently.

Learn More on WordPress.org

Register an account to save your snippets or go Pro to get more features.