WordPress.org

Ready to get started?Download WordPress

Forums

A way to retrieve top level category of a post? (2 posts)

  1. Jack
    Member
    Posted 7 years ago #

    I have to find a way to get the top level category of a post.

    I have a few categories that function as top level category. They have no posts themselves. Beneath them are a few categories that contain posts. When I click one of them, for instance index.php?p=23 I want to know to what top level category this post belongs to, like this:

    Animals
    - Dogs
    -- Golden Retriever
    -- Husky
    -- Rottweiler

    In this case Golder Retriever belongs to top category 'Animals'.

    Is there a way or a plugin that can do this? I need it to show a different image at the top of the page.

  2. alexbalint
    Member
    Posted 6 years ago #

    Hi there - found a solution! I needed this to show a full category tree in the sidebar, but the image idea is great also :)

    The code is this:

    function get_topLevelParent ($postid) {
    $pdata = get_post($postid);
    $parent = $pdata->post_parent;
    if ($parent != 0) {
    $r = get_topLevelParent($parent);
    } else {
    $r = $postid;
    }
    return $r;
    }

    This function returns the top-level parent of any post. You can use it to build a sidebar with all children of a 'master category'.

    You can feed the current post ID to the function (it should work, I gave the parent ID anyway). Hope this solves your problem (even a little bit late :) )

Topic Closed

This topic has been closed to new replies.

About this Topic

Tags