问题描述:

I have a website with food products and I have a custom post type called recipes.

What I need to do is to display 3 posts from the recipe-categories attached to the product.

I have created and attached the custom post type to my products but I just can't get it to work!I am kind of lost. I have managed to loop through the recipes and get 3 posts but I don't know how to filter out the categories for the recipes.

Example:

-Recipe Categories

Sauce

Spicy

Lets say I have a product "Noodle" and I want to show 3 posts from Sauce category. I can't manage to display it. I am always getting posts from every single Recipe Category.

This is my loop to show the 3 posts.

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

I have tried to add taxonomy categories to my array arguments but nothing happens!

Here is what i tried to do(with many variations):

$mytaxonomy = 'recipe_category';

$myterms = get_the_terms($post, $mytaxonomy);

and then I used the same while as above with adding the terms in the array.

Can someone please help me? I am lost and stuck but I need to know why it doesn't work so I can improve myself.

网友答案:

WP_Query also support tax_query for getting post by category, give it a try:

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

Hope this helps!

相关阅读:
Top