0

Using the Enhanced Media Library plugin, I have added custom media categories and am now trying to apply those categories as classes for images shown in the [gallery] shortcode. This is the code I'm using (inside a custom [gallery] shortcode):

        $terms = get_terms('media_category', array('parent' => '15'));

        foreach ( $terms as $id => $term ) {
            $term = $term->slug;
        }

This code is outputting the category names as classes, however it's applying the categories only from the first image in the gallery to every single other image, and ignoring the categories of the other images.

As I have incorporated Isotope, I'm also using the media categories to sort the gallery. This code is working correctly:

$terms = get_terms('media_category', array('parent' => '15'));
      $count = count($terms);
           if ( $count > 0 ){
               foreach ( $terms as $term ) {
                  echo "<button type='button' class='btn'  data-hover='" . $term->name . "' data-filter='." . $term->slug . "'>" . $term->name . "</button>\n";
               }
            }

What is it I've missed on the first piece of code?

0

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'>";

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.