Body class function with parent slug class

The roots_ body_class function ia a great feature, but it only adds the current page slug. How would it be possible to change the code, so that it also shows it’s top parent (or all parents if easier) slugs?

$classes[] = basename(get_permalink());

The reason for this is, that i will have different colours for each page/category and i think this is the easiest way to do it. I tried my luck but i’m still picking up php so it’s a bit over my head for now.


It’s always better to try before asking for help: it’s the quickest way to learn.

  1. You can use get_post_ancestors to find the parents by passing the post object or the post id.
  2. You can use end to return the last array item (which the codex link in 1. says is the top-level parent, ).
  3. You can reuse the default code but pass the result of step 2 to get_permalink.