我在Wordpress网站上使用ACF关系字段,这样管理员用户就可以轻松地确定哪些帖子在该页面上可见。我有一个自定义的分类法,我需要能够get_the_terms
并为每个帖子打印术语。这是正常的实现与foreach提到的代码。
然而,我使用foreach来获得$posts
,所以我不知道如何使用它来打印我的H3
中的术语名称和主<div>
中的术语段塞
以下代码:
<?php
$posts = get_field('team_members',12);
$terms = get_the_terms( $post->ID , 'position' );
if( $posts ): ?>
<?php foreach( $posts as $post): // variable must be called $post (IMPORTANT)
setup_postdata($post); ?>
<div class="col-4 col <?php echo $term->slug;?>">
<article id="post-<?php the_ID(); ?>" <?php post_class('team-item'); ?>>
<hgroup>
<?php the_title( sprintf( '<h2 class="alt-heading-4">', esc_url( get_permalink() ) ), '</h2>' ); ?>
<h3><?php echo $term->name;?></h3>
</hgroup>
<div class="team-entry-content">
<?php the_content();?>
</div><!-- .entry-content -->
<div id="team-shadow"></div>
</article><!-- #post-## -->
</div>
<?php endforeach; ?>
<?php wp_reset_postdata();?>
<?php endif; ?>
由于术语与您的帖子相关联,您必须放置:
$terms = get_the_terms( $post->ID , 'position' );
在foreach循环内部,在外部它根本不起作用,因为$post->ID
将出错:
trying to get the property of non object
因此,解决方案是取$terms = get_the_terms( $post->ID , 'position' );
并将其添加到foreach循环中:
<?php
$posts = get_field('team_members',12);
if( $posts ): ?>
<?php foreach( $posts as $post): // variable must be called $post (IMPORTANT)
setup_postdata($post);
$terms = get_the_terms( $post->ID , 'position' ); ?>
<div class="col-4 col <?php echo $term->slug;?>">
<article id="post-<?php the_ID(); ?>" <?php post_class('team-item'); ?>>
<hgroup>
<?php the_title( sprintf( '<h2 class="alt-heading-4">', esc_url( get_permalink() ) ), '</h2>' ); ?>
<?php foreach($terms as $term) {?>
<h3><?php echo $term->name;?></h3>
<?php } ?>
</hgroup>
<div class="team-entry-content">
<?php the_content();?>
</div><!-- .entry-content -->
<div id="team-shadow"></div>
</article><!-- #post-## -->
</div>
<?php endforeach; ?>
<?php wp_reset_postdata();?>
<?php endif; ?>
我希望它确实有所帮助:)。