[英]Wordpress Custom Post Type Taxonomy - Get specific content
我有一個食品網站,我有一個自定義的帖子類型,稱為食譜。 我需要做的是從附加到產品的配方類別中顯示 3 個帖子。 我已經創建並將自定義帖子類型附加到我的產品,但我無法讓它工作!我有點迷失了。 我已經設法遍歷食譜並獲得 3 個帖子,但我不知道如何過濾食譜的類別。
例子:
-Recipe Categories
Sauce
Spicy
假設我有一個產品“面條”,我想顯示醬類類別的 3 個帖子。 我無法設法顯示它。 我總是收到來自每個食譜類別的帖子。
這是我顯示 3 個帖子的循環。
<?php $loop = new WP_Query( array( 'post_type' => 'recipes', 'posts_per_page' => 3 ) );
while ( $loop->have_posts() ) : $loop->the_post(); ?>
<a href="<?php the_permalink(); ?>">
<img src="<?php the_post_thumbnail_url(); ?>">
<h4><?php the_title(); ?></h4>
</a>
<?php endwhile; ?>
我試圖將分類類別添加到我的數組參數中,但沒有任何反應! 這是我嘗試做的(有很多變化):
$mytaxonomy = 'recipe_category';
$myterms = get_the_terms($post, $mytaxonomy);
然后我使用與上面相同的方法在數組中添加術語。 有人可以幫幫我嗎? 我迷路了,卡住了,但我需要知道為什么它不起作用,這樣我才能提高自己。
WP_Query 還支持tax_query
按類別獲取帖子,試試看:
global $post;
$terms = get_the_terms($post->ID, 'recipe_category');
$recipe_cat_slug = array();
foreach ($terms as $term)
{
$recipe_cat_slug[] = $term->slug;
}
$args = array(
'post_type' => 'recipes',
'posts_per_page' => 3,
'tax_query' => array(
array(
'taxonomy' => 'recipe_category',
'field' => 'slug', //can be set to ID
'terms' => $recipe_cat_slug //if field is ID you can reference by cat/term number; you can also pass multiple cat as => array('sauce', 'spicy')
)
)
);
$loop = new WP_Query($args);
希望這可以幫助!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.