Media Categories as Classes on WordPress Gallery Shortcode

OK, so I figured out what I was doing wrong.

What I had originally tried was the foreach on its own and then placing the gallery output below it. I also tried wrapping the foreach around the entire gallery output.

To get it working, I needed to wrap the foreach around the output of the itemtag in the gallery shortcode:

        $terms = wp_get_post_terms( $id, 'media_category', array( 'fields' => 'all' ) );

    $output .= "<{$itemtag} class="gallery-item {$orientation}";

    foreach ( $terms as $term ) {
        if ($term->parent != 0) {
        $term = $term->slug;

            $output .= " {$term}";

        }
    }

    $output .= "" itemprop='associatedMedia' itemscope itemtype="http://schema.org/ImageObject">";