Question

I have custom post types with taxonomies in them (for example Custom post type: Recipes; Taxonomies in the Recipes: Ingredients, Preparation Time, Difficulty). In my homepage I want to run wp_query to display the latest 5 Recipes. So far so good, but when I can't manage to get the taxonomy entries for the post

I use the following code:

<?php query_posts( array( 'meta_key' => 'ratings_average', 'orderby' => 'meta_value_num', 'order' => 'DESC', 'post_type' => 'muffins', 'showposts' => 1) );   
        while ( have_posts() ) : the_post(); ?>
    <div class="recipe">
        <?php the_post_thumbnail(array(272,150)); ?>
        <a href="<?php the_permalink(); ?>" alt="<?php the_title(); ?>"><p class="title"><?php the_title(); ?></p>
        <p class="recipe-contents"><?php the_excerpt(); ?></p></a>
        <ul>
            <li>Preparation time: (I need function to extract the taxonomy term for this post - The taxonomy is 'time')</li>
            <li>Difficulty: (same here ... the taxonomy is 'difficulty'</li>
            <li>Servings: (and once again the taxonomy is 'servings'</li>
        </ul>    
    <?php endwhile;?>
Était-ce utile?

La solution

You'll need to do something with the_terms which is the WordPress function for pulling out taxonomy data.

Something similar to below:

<?php query_posts( array( 'meta_key' => 'ratings_average', 'orderby' => 'meta_value_num', 'order' => 'DESC', 'post_type' => 'muffins', 'showposts' => 1) );   
        while ( have_posts() ) : the_post(); ?>
    <div class="recipe">
        <?php the_post_thumbnail(array(272,150)); ?>
        <a href="<?php the_permalink(); ?>" alt="<?php the_title(); ?>"><p class="title"><?php the_title(); ?></p>
        <p class="recipe-contents"><?php the_excerpt(); ?></p></a>
        <ul>
            <li>Preparation time: <?php the_terms( get_the_ID(), 'time'); ?> </li>
            <li>Difficulty: <?php the_terms( get_the_ID(), 'difficulty'); ?></li>
            <li>Servings: <?php the_terms( get_the_ID(), 'servings'); ?></li>
        </ul>    
    <?php endwhile;?>

You can read more about the_terms() here and how you can better use it with more styling, separators etc.

Hopefully this should answer your question.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top