对于每个帖子,将每个术语添加到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 );
}