[英]get posts using taxonomy in wordpress
我的計算機上本地安裝了一個 wordpress 應用程序。 在 wordpress 管理員中,我在“帖子”下有一個“國家/地區”選項卡。 我會附上一張圖片以便更好地理解。
我想寫一個 function 來為我的前端獲取國家/地區值。 為此,我寫了一個 function 這樣的
public function get_destinations()
{
$bookings = get_posts(
array(
'taxonomy'=> 'country',
'numberposts' => -1,
)
);
return $bookings;
}
但是由於某種原因,這個 function 返回了數據庫中的所有帖子。 我只想獲得國家名稱。
我從本地 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
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.