Support » Developing with WordPress » How to get the last category slug of a child category?

  • jaytp


    Hi, there. I’ve tried tons of solutions I’ve found in this forum before asking this. It’s kind of hard for me to understand the php sintaxe. I have no idea how to do this and i’ve been stuck for days trying hundreds of codes. Can someone help me?

    I have the following categories:

    - Animal
    -- Dog
    --- frenchie-1
    --- frenchie-2
    --- frenchie-3`

    `Animal > Dog > frenchie-3

    I need to get the slug from “frenchie-3”, that is the last one in this situation. Maybe in the future will be a frenchie-4 and I would need to retrieve this “new last” category of that child category. I will always need the last one.

    Thanks a lot for your attention.

Viewing 2 replies - 1 through 2 (of 2 total)
  • Moderator bcworkz


    What constitutes “last” should be clearly defined in terms of the database schema. I think you want the most recently added term that’s a child of “Dog”, correct? The problem is terms do not keep any date or time data. However, we can query for child terms with no ordering criteria at all. Then the returned terms should be in the order found in the DB table (unverified). Not a 100% reliable approach, but I think it’ll work. Something like:

    $parent_id = 123; // <--- determine correct term ID for "Dog"
    $cats = get_categories([
      'parent'=> $parent_id,
    $last_slug = $cats[count($cats)-1]->slug;

    The reliable alternative would involve custom code that saves date data on terms added, and assigning date data to existing terms that matter.

    Hi @jaytp

    Try this function:

    function misha_get_last_cat_slug() {
        $categories = get_the_category();
            $last_category = $categories[0];
            foreach($categories as $category) {
                if($category->parent == $last_category->cat_ID ) {
                    $last_category = $category;
            return $last_category->slug;
Viewing 2 replies - 1 through 2 (of 2 total)
  • You must be logged in to reply to this topic.