在 Wordpress 循环中返回对象 slug


Returning object slug inside of Wordpress loop

我有一个变量$terms,其中包含:

 Array ( 
   [230] => stdClass Object ( 
      [term_id] => 230
      [name] => Executive Committee 
      [slug] => executive_committee
      [term_group] => 0 
      [term_taxonomy_id] => 241 
      [taxonomy] => team_member_filter
      [description] =>
      [parent] => 0 
      [count] => 1 
      [object_id] => 1561 
      [filter] => raw 
   )   
)
每个帖子

都包含这个数组,显然每个帖子的"230"键是不同的。 在默认的wordpress循环中,我可以print_r($terms),它为每个帖子返回此数组。 我需要回显每个帖子的"slug"值。 我可以通过编写 $terms[230]->slug 来吐出 slug 值,但这当然只返回第一个实例。如何在循环中返回每个帖子的"slug"值?

这是我的循环:

<?php $args = array('post_type' => 'team-member','posts_per_page'=>-1,'order'=>'DESC','orderby'=>'date'); ?>
<?php query_posts($args); ?>
<?php $terms = get_the_terms(get_the_ID(), 'team_member_filter'); ?>
    <?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>
        <!-- Get the taxonomy -->
        <?php print_r($terms[230]->slug); ?>
   <?php endwhile; ?>

如何替换"230"以便获得每个帖子的"slug"值。

您在循环外使用get_the_terms,因此它返回第一篇文章的术语。当您循环浏览帖子时,它不会改变。

在循环内移动$terms = ...

<?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>
    <?php $terms = get_the_terms( get_the_ID(), 'team_member_filter' ); ?>

接下来$terms是一个数组。我建议循环播放它。

<?php if ( $terms && ! is_wp_error( $terms ) ) { 
    foreach ( $terms as $term ) {
        echo $term->slug; // don't forget to format.
    }
} ?>

如果您确定只有一个,则始终可以执行以下操作:

<?php echo current( $terms )->slug; ?>

如果您确实采取了这条路线,那么可能值得保留 if 语句,以防万一出现问题。