Wordpress自定义文章类型分类-获取特定内容



我有一个食品网站,还有一个名为recipes的自定义帖子类型。我需要做的是显示产品附带的配方类别中的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);

然后我使用了与上面相同的while,添加了数组中的项。有人能帮帮我吗?我迷失了方向,陷入了困境,但我需要知道为什么它不起作用,这样我才能提高自己。

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);

希望这能有所帮助!

最新更新