【问题标题】:How to display current posts custom taxonomy name inside wordpress loop?如何在 wordpress 循环中显示当前帖子自定义分类名称?
【发布时间】:2016-02-22 12:03:42
【问题描述】:

我目前正在构建一个 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 工作的; ?> 显示班级名称但是它只在每个班级名称上显示“兽医”,而它应该在每个项目上显示相关部门......

希望这是有道理的。

非常感谢。

【问题讨论】:

    标签: php wordpress


    【解决方案1】:

    对于任何感兴趣的人,我现在已经解决了这个问题:

    &lt;?php $term_list = wp_get_post_terms($post-&gt;ID, 'department', array("fields" =&gt; "all")); ?&gt;

    并通过使用

    &lt;?php echo $term_list[0]-&gt;slug ;  ?&gt;

    作为类名。

    谢谢

    【讨论】:

      【解决方案2】:

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

      【讨论】:

        猜你喜欢
        • 2013-03-08
        • 1970-01-01
        • 1970-01-01
        • 2016-08-08
        • 2015-11-09
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多