I am not a coder, but I usually get by with Wordpress by doing my research and find my solution. I can't find what I need to do this time so I have attempted to crib together some code - what I am attempting to do is, when I am on the Category Archive, I want to add a body class of the category parent. This is what I have tried and it is working apart from I am getting the parents category ID, but I want the slug/nicename:

  function hw_custom_body_class($classes){
  $categories = get_the_category();
  $category = strtolower($categories[0]->category_parent);
  return $classes;    }}

Use get_ancestors() to get the parent terms. Here is an excerpt from my plugin T5 Parent Terms in body_class:

    $ancestors = get_ancestors(

    if ( empty ( $ancestors ) )
        return $classes;

    foreach ( $ancestors as $ancestor )
        $term          = get_term( $ancestor, get_queried_object()->taxonomy );
        $new_classes[] = esc_attr( "parent-$term->taxonomy-$term->slug" );

This will work with any taxonomy, not just categories.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.