简体   繁体   English

如何在wordpress循环中显示当前帖子的自定义分类名称?

[英]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.. 我目前正在建立一个Wordpress网站,但遇到以下困难。

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. 我试图通过显示当前帖子类型的自定义分类名称来动态添加类到HTML元素,以用作类名称。 This is all being done within a Foreach loop. 这些都是在Foreach循环中完成的。

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 您也可以通过此代码解决此问题,将此代码放入while循环中,“ portfolio_category”是自定义分类法名称

$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; 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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