How to Get Post Ancestors in WordPress

Home » Snippets » How to Get Post Ancestors in WordPress

Created with:



Creator: WPTurbo Team

Customize with WPTurbo AI

Add Snippet To Project

New Project
Add To Existing Project

If you’re a WordPress developer or a web development enthusiast, you may have encountered situations where you need to retrieve the ancestors of a specific post. Whether it’s for creating a breadcrumb navigation or for displaying hierarchical relationships between posts, the ability to fetch post ancestors is an essential tool in your WordPress arsenal. In this article, we’ll explore different methods and techniques to easily get the ancestors of a post, allowing you to enhance your WordPress websites with organized and interconnected content.

					function wpturbo_get_post_ancestors() {
    global $post;
    $ancestors = [];
    if($post->post_parent) {
        $ancestors = get_post_ancestors($post->ID);
    return $ancestors;

$post_ancestors = wpturbo_get_post_ancestors();

The code snippet above demonstrates how to retrieve and store the ancestors of a post in WordPress.

First, we define a function called wpturbo_get_post_ancestors(). Within this function, we declare a global variable $post which allows us to access information about the current post. We also initialize an empty array called $ancestors which will store the post ancestors.

Next, we check if the current post has a parent by using the if statement with the condition $post->post_parent. If the condition evaluates to true, we execute the code inside the curly brackets.

Inside the if statement, we call the get_post_ancestors() function passing the post ID ($post->ID) as its argument. The get_post_ancestors() function retrieves an array of the post ancestors and assigns it to the $ancestors variable.

Finally, outside the if statement, we return the $ancestors array.

To use this function, we assign the result of the wpturbo_get_post_ancestors() function to a variable called $post_ancestors. This variable will contain the array of post ancestors. You can then use this array as needed in your WordPress theme or plugin.

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