在 wordpress 中使用分类法获取帖子
get posts using taxonomy in wordpress
我在我的计算机上本地安装了一个 wordpress 应用程序。在 wordpress 管理员中,我在帖子下有一个国家选项卡。我会附上一张图片以便更好地理解。
我想编写一个函数来为我的前端获取国家/地区值。为此我写了一个这样的函数
public function get_destinations()
{
$bookings = get_posts(
array(
'taxonomy'=> 'country',
'numberposts' => -1,
)
);
return $bookings;
}
但由于某种原因,此函数 returns 数据库中的所有帖子。我只想获得国家名称。
我从本地 url 找到了分类法
http://localhost/my_project/wp-admin/edit-tags.php?taxonomy=country
我是 wordpress 的新手,不知道如何将这些数据检索到我的前端。我在这里做错了什么?
如果您想显示唯一的类别或分类名称而不是 get_posts,您必须使用 get_terms
检查此代码。
// Get the taxonomy's terms
$terms = get_terms(
array(
'taxonomy' => 'country',
'hide_empty' => false, // show category even if dont have any post.
)
);
// Check if any term exists
if ( ! empty( $terms ) && is_array( $terms ) ) {
// Run a loop and print them all
foreach ( $terms as $term ) { ?>
<a href="<?php echo esc_url( get_term_link( $term ) ) ?>">
<?php echo $term->name; ?>
</a><?php
}
}
我在我的计算机上本地安装了一个 wordpress 应用程序。在 wordpress 管理员中,我在帖子下有一个国家选项卡。我会附上一张图片以便更好地理解。
我想编写一个函数来为我的前端获取国家/地区值。为此我写了一个这样的函数
public function get_destinations()
{
$bookings = get_posts(
array(
'taxonomy'=> 'country',
'numberposts' => -1,
)
);
return $bookings;
}
但由于某种原因,此函数 returns 数据库中的所有帖子。我只想获得国家名称。
我从本地 url 找到了分类法
http://localhost/my_project/wp-admin/edit-tags.php?taxonomy=country
我是 wordpress 的新手,不知道如何将这些数据检索到我的前端。我在这里做错了什么?
如果您想显示唯一的类别或分类名称而不是 get_posts,您必须使用 get_terms
检查此代码。
// Get the taxonomy's terms
$terms = get_terms(
array(
'taxonomy' => 'country',
'hide_empty' => false, // show category even if dont have any post.
)
);
// Check if any term exists
if ( ! empty( $terms ) && is_array( $terms ) ) {
// Run a loop and print them all
foreach ( $terms as $term ) { ?>
<a href="<?php echo esc_url( get_term_link( $term ) ) ?>">
<?php echo $term->name; ?>
</a><?php
}
}