0
votes

I am trying to display a list of the terms and descriptions from a custom taxonomy.

I have the following code which returns all terms with descriptions of a specified custom taxonomy in alphabetical order. However, I only want to show the five most recent terms, starting with the newest one.

<?php 

$terms = get_terms('mytaxonomy'); 
if ( !empty( $terms ) && !is_wp_error( $terms ) ){ 
echo '<ul>'; 

foreach ( $terms as $term ) { 
   $term = sanitize_term( $term, 'mytaxonomy' ); 
   $term_link = get_term_link( $term, 'mytaxonomy' ); 

    echo '<li><a href="' . esc_url( $term_link ) . '">' . $term->name . '</a><p>' . $term->description . '</p></li>'; 
} 
echo '</ul>';
}

?> 
2

2 Answers

0
votes

try this:

$terms = get_terms('mytaxonomy'array('orderby'=>'date','order'=>'ASC','number'=>5));

This is will return your recent 5 terms of this taxonomy. For more reference, you can check the codex of wordpress: https://developer.wordpress.org/reference/functions/get_terms/

0
votes

I have found a solution, but I am sure there is a more elegant way of achieving this:

<?php $catquery = new WP_Query( 'cat=332&posts_per_page=5' ); ?>
    <div class="category-posts">
        <?php while($catquery->have_posts()) : $catquery->the_post(); ?>
            <div class="category-item">
                <?php
                $terms = get_the_terms($post->ID , 'mytaxonomy' );
                    if ( ! empty( $terms ) && ! is_wp_error( $terms ) ){
                        if( $terms ){
                            $term = array_shift( $terms );
                            echo '<a href="/' . $term->slug . '">' . $term->name . '</a><p>' . $term->description . '</p>';
                        }
                    }
                ?>
            </div>
        <?php endwhile; ?> 
    </div>
<?php wp_reset_postdata(); ?>

The code above takes the 5 most recent posts from a category (in this case: 332) and lists the first term of a custom taxonomy (in this case: mytaxonomy) for each of these posts.

This works for me, because all posts with that custom taxonomy are always in the same category. However, this will not work if they are in different categories.