dynamically adding multiple classes to wordpress body_class()

I’m trying to figure out how to add add terms for pages to my body class automatically. I’m very close with some code I’ve been piecing together. Right now this works, but only returns one term. How can I get it to return an array of terms each as a class that get’s added to the body tag? Here’s what I’ve got so far. fyi “topbar” is my taxonomy name.

<?php $class='';
  if(is_page()) {
  $terms = get_terms("topbar");
  $class .= $terms[0]->slug;
}?>
<body id="top" <?php if (function_exists('body_class')) body_class($class ); ?>>

Related posts

Leave a Reply

1 comment

  1. <?php
    if(is_page()) {
        global $post;
        $terms = wp_get_post_terms($post->ID, "topbar", array("fields" => "names"));
        $class = ($terms) ? implode(" ", $terms) : '';
    }
    ?>
    
    <body id="top" <?php if (function_exists('body_class')) body_class($class ); ?>>
    

    Cheers 😉