首页 文章

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

提问于
浏览
0

我目前正在构建一个Wordpress网站,我遇到了以下一些困难..

我试图通过显示当前帖子类型的自定义分类名称来动态地将类添加到HTML元素,以用作类名 . 这一切都是在Foreach循环中完成的 .

我的代码如下

<?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();?>

这是使用slug工作; ?>显示 class 名称但是它只在每个 class 名称上显示“兽医 - 外科医生”,当它应该显示每个项目的相关部门时......

希望有道理 .

非常感谢 .

2 回答

  • 0

    对于任何有兴趣的人我现在用以下方法解决了这个问题

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

    并通过使用

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

    作为 class 名称 .

    谢谢

  • 1

    您也可以通过此代码解决此问题,将此代码放在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;
    

相关问题