0

I have this situation where I need to filter specific post type posts by its taxonomies (there 3 different ones) and since I am using Isotope, I need them in my class element. I already made it work with one and I believe I took the 'long' road. I dont really work that much with php, this is what I could get from codex...

1) I get custom post type entries 2) inside

$terms = get_the_terms( $post->ID, 'resource_roles' );  
if ( $terms && ! is_wp_error( $terms ) ) : 

    $links = array();

    foreach ( $terms as $term ) {
        $links[] = $term->name;
    }

    $tax_links = join( " ", str_replace(' ', '-', $links));          
    $tax = strtolower($tax_links);
else :  
    $tax = '';                  
endif; 

echo '<div class="color-shape resource-block ' . $tax . '">';
echo '<h1>' . the_title() . '</h1>';
echo '</div>';

As seen in the code, now it ads 'resource_roles' taxonomy elements, now I need to add 'resource_media' and 'resource_theme'. :/ I believe there is shorter way, community, can you help me make this code neat and short?

1 Answer 1

1

If using get_the_terms, you can just do your if loop once for each taxonomy and then join them after the three loops.

Of course, it would probably be more efficient to use:

wp_get_post_terms( $post_id, $taxonomy, $args );

You could then do something like:

wp_get_post_terms( $post_id, array( 'resource_roles', 'resource_media', 'resource_theme' ) );

Which would pull all of the terms in one query.

To echo them into your class attribute, use the code you use when they are all the same type:

$extra_classes = '';
$terms = wp_get_post_terms( $post_id, array('resource_roles','resource_media','resource_theme');
if ( is_wp_error( $terms ) ) {
   # Log the error, notify someone, etc.
} else if ( 0 < count( $terms ) ) {
   $slugs = array();
   foreach ( $terms as $term ) {
      $slugs[] = $term->slug;
   }
   $extra_classes = implode(' ', $slugs);
}
$title = get_the_title();
echo <<<HTML
<div class="color-shape resource-block {$extra_classes}">
   <h1>{$title}</h1>
</div>
HTML;
2
  • Hi, if i get terms in one query, how can i expose them to echo into my class attribute? Commented Jan 20, 2015 at 20:21
  • updated to show how to put them to use.
    – Privateer
    Commented Jan 23, 2015 at 4:07

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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