Question

I have a custom taxonomy called Issues (like magazine issues) with categories named after the title of each issue. I created a page called "Current Issue" and added a link to it in the main navigation of the site.

This is the loop I have in the page template now:

$categories = get_terms('issue', 'orderby=count&order=asc');
     foreach( $categories as $category ): 
     ?>
     <h3><?php echo $category->name; ?></h3>
     <?php
     $posts = get_posts(array(
     'post_type' => 'issue_posts',
     'taxonomy' => $category->taxonomy,
     'term' => $category->slug,
     'nopaging' => true,
     ));
     foreach($posts as $post): 
     setup_postdata($post); 

It does order the categories and posts appropriately, but this pulls in all the posts for all the categories. I need the link to show only the most recently added category.

Était-ce utile?

La solution

The most recently added term will be the one with the highest ID. Fetch a single term ordered by ID in descending order and you will have the one most recently added.

$args = array(
    'number' => 1,
    'orderby' => 'ID',
    'order' => 'DESC'
);

$recent_issue = get_terms( 'issue', $args );

Autres conseils

Because categories are a taxonomy in Wordpress, there is no date associated with them to tell you what the "most recent" one is. If you need to keep track of what the most recently created category is, you could use the created_term, which in the Wordpress source is in /wp-includes/taxonomy.php and function wp_insert_term():

do_action("created_term", $term_id, $tt_id, $taxonomy);

The $taxonomy for a category will be category (check before saving), and the $term_id will be the your category ID. From your function hooked to this action, you can call update_option('latest_category_id', $term_id); and then fetch it later with get_option('latest_category_id'); for use in your get_posts() call.

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