【发布时间】:2016-02-10 08:05:09
【问题描述】:
我在 Wordpress 网站上使用 ACF relationship 字段,以便管理员用户可以轻松确定该页面上可见的帖子。我有一个自定义分类法,我需要能够get_the_terms 并打印每个帖子的术语。这通常通过 codex 中提到的 foreach 来实现。
但是我使用 foreach 来获取 $posts,所以我不确定如何使用它来打印我的 H3 中的术语名称和主 <div> 中的术语 slug
代码如下:
<?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; ?>
【问题讨论】:
-
所以我不需要阅读大量文档,
get_the_terms()调用中使用的$post->ID是否与foreach ($posts as $post)迭代中定义的$post相关,或者是@987654332 @ 来自早期代码的变量?换句话说,您是否正在检索从get_field()循环的每个帖子ID的术语? -
$post->ID 未在 get_the_terms 中使用。一切都会保持原样,除了 foreach 看起来像 'foreach($terms as $term)'
-
由于对 WP 不熟悉,我并不能完全确定其意图,但在我看来,您需要在外部
foreach ($posts as $post)内部执行的操作是另一个嵌套在其中的foreach ($terms as $term),其中您将调用移动到get_the_terms()以发生 inside $postsforeach循环而不是在它之前。但正如我所说,我对 WP 不熟悉.... -
我的意思是算法:
$posts = get_field()...foreach($posts as $post) { $terms = get_the_term()... foreach ($terms as $term) { //print term info } }
标签: php wordpress foreach advanced-custom-fields