我已经找了半天了,但到目前为止还没有成功。
我创建了一个自定义帖子类型(recipe)和两个与之配套的自定义分类法(type和cook)。我想要的是能够列出一组食谱中的所有“厨师”。
我可以用一个食谱来做,但我只能用多个。
有没有人知道如何做到这一点?
我已经找了半天了,但到目前为止还没有成功。
我创建了一个自定义帖子类型(recipe)和两个与之配套的自定义分类法(type和cook)。我想要的是能够列出一组食谱中的所有“厨师”。
我可以用一个食谱来做,但我只能用多个。
有没有人知道如何做到这一点?
对于每个帖子,将每个术语添加到PHP关联数组:
foreach ( $posts as $post ) {
$term_objects = get_the_terms( $post->ID, $taxonomy_name );
foreach ( $term_objects as $term_object ) {
// Store term objects by term name.
$terms_list[ $term_object->name ] = $term_object;
}
}
比如说,鲍勃被列为前两份食谱中的厨师。处理第一篇帖子时,会出现一个名为Bob
已添加到$terms_list
. 在第二根柱子上Bob
字段被相同的信息覆盖(术语对象)。遍历所有帖子后的结果是一个列表key => values
钥匙是唯一的<例如,Bob只列出一次。
由于您没有提供任何代码或告诉我们您想要的输出应该是什么样子,因此我使用get_posts()
函数获取帖子数组,并使用无序列表将厨师姓名显示为链接。
$cooks = wpse_125356_get_terms_for_posts( get_posts( array( \'post_type\' => \'recipe\' ) ), \'cook\' );
if ( $cooks ) {
echo "<ul>\\n";
foreach ( $cooks as $cook ) {
$url = get_term_link( $cook );
if ( is_wp_error( $url ) ) {
echo "\\t<li>{$cook->name}</li>\\n";
} else {
echo "\\t<li><a href=\'{$url}\'>{$cook->name}</a></li>\\n";
}
}
echo "</ul>\\n\\n";
}
/**
* Get all unique terms for an array of posts for a given taxonomy.
*
* @param array $posts An array of post objects.
* @param string $taxonomy_name The name of the taxonomy to retrieve.
* @return array An array term objects ordered by term name.
*/
function wpse_125356_get_terms_for_posts( array $posts, $taxonomy_name ) {
$terms_list = array();
foreach ( $posts as $post ) {
$term_objects = get_the_terms( $post->ID, $taxonomy_name );
// $term_objects can also be boolean false or a WP_Error object.
if ( is_array( $term_objects ) ) {
foreach ( $term_objects as $term_object ) {
// Store term objects by term name.
$terms_list[ $term_object->name ] = $term_object;
}
}
}
// Sort term objects by term name.
ksort( $terms_list );
// Return a list of term objects, if any.
return array_values( $terms_list );
}
嗨,我目前正在为我的博客构建一个主题。下面的代码指向最新的帖子(特色帖子)。因为这将有一个不同的风格比所有其他职位。然而我想过滤掉帖子格式:链接使用我在循环中定义的WP查询,因为它给我带来了更多的灵活性。我该怎么做呢? <?php $featured = new WP_Query(); $featured->query(\'showposts=1\'); ?> <?php while ($featured->have_post