简体   繁体   中英

How to display current posts custom taxonomy name inside wordpress loop?

I am currently building a Wordpress site and I am encountering some difficulty with the following..

I am trying to dynamically add a class to a HTML element by displaying the custom taxonomy name of the current post type, to use as the class name. This is all being done within a Foreach loop.

My code is as follows

 <?php $args = array( 'posts_per_page' => -1, 'post_type' => 'staff', 'orderby' => 'menu_order', 'order' => 'DESC'); $myposts = get_posts( $args ); foreach ( $myposts as $post ) : setup_postdata( $post ); ?> <?php $terms = wp_get_post_terms( $post_ID, 'department' ); ?> <?php global $post; $terms = wp_get_post_terms( $post->ID, 'department'); ?> <div class="grid-item <?php echo $term->slug; ?> "> <div class="staff-box"> <?php the_post_thumbnail('staff-member'); ?> <a href="<?php echo the_permalink(); ?>"> <p class="staff-title"><?php the_title(); ?></p> <p class="staff-job-title"><?php the_field('staff-job-title'); ?></p> </a> </div> </div> <?php endforeach; wp_reset_postdata();?> 

This is working using slug; ?> to display the class name however it is only displaying "veterinary-surgeons" on every single class name, when it should be displaying the relevant department on each item...

Hope that makes sense.

Many thanks.

To anyone who is interested I have now solved this using:

 <?php $term_list = wp_get_post_terms($post->ID, 'department', array("fields" => "all")); ?> 

and by using

 <?php echo $term_list[0]->slug ; ?> 

as class name.

Thanks

You can solve this problem by this code also, Put this code inside while loop, 'portfolio_category' is custom taxonomy name

$terms = get_the_terms( $post->ID, 'portfolio_category' );  

                            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; 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM