Skip to content

Instantly share code, notes, and snippets.

@thefuxia
Last active September 5, 2024 01:32
Show Gist options
  • Save thefuxia/2930463 to your computer and use it in GitHub Desktop.
Save thefuxia/2930463 to your computer and use it in GitHub Desktop.
Parent Terms in body_class
<?php # -*- coding: utf-8 -*-
/**
* Plugin Name: T5 Parent Terms in body_class
* Description: Adds all parent terms of a term archive to <code>body_class()</code>.
* Version: 2012.0.14
* Author: Fuxia Scholz
* License: MIT
* License URI: http://www.opensource.org/licenses/mit-license.php
*/
add_filter( 'body_class', 't5_parent_terms_to_body_class' );
function t5_parent_terms_to_body_class( $classes )
{
if ( ! isset ( get_queried_object()->taxonomy ) && ! is_singular() )
{
return $classes; // not a term archive and not a single page
}
$current_terms = array ();
$new_classes = array ();
if ( is_singular() )
{
$post_id = get_the_ID();
$post = get_post( $post_id );
$taxonomies = get_object_taxonomies( $post );
$terms = array ();
if ( empty ( $taxonomies ) )
{
return $classes;
}
foreach ( $taxonomies as $taxonomy )
{
$tax_terms = get_the_terms( $post_id, $taxonomy );
! empty ( $tax_terms) and $terms = array_merge( $terms, $tax_terms );
}
foreach ( $terms as $term )
{
if ( 0 !== $term->parent )
{
$term_ancestors = get_ancestors(
$term->term_id,
$term->taxonomy
);
foreach ( $term_ancestors as $term_ancestor )
{
$term_data = get_term( $term_ancestor, $term->taxonomy );
$new_classes[] = esc_attr( "parent-$term->taxonomy-$term_data->slug" );
}
}
}
}
else
{
// get all ancestors as an array.
$ancestors = get_ancestors(
get_queried_object_id(),
get_queried_object()->taxonomy
);
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" );
}
}
// combine both
$classes_out = array_merge( $classes, $new_classes );
return array_unique( $classes_out );
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment