0

I have an interesting problem that I could use some help resolving.

I need to know if there is a way to grab posts from the most recently created category in WordPress.

My client has a magazine type theme going on. I am using the default category creation functionality of WP to allow them to create new "issues" each month. The category is actually the month and year. Think of a magazine, where for example the current issue(Category) is March 2015. They will create a new issue(Category) each month, and of course articles will be posted in sub categories of the current issue(Category).

How can I grab posts from the most recently created category for each month to display on the front end? This way in a table of contents it would look something like:

  • March 2015 (Main, or "current" Category)
    • Sub Category
      • Article Title
      • Article Title
      • Article Title
    • Sub Category
      • Article Title
      • Article Title
      • Article Title

etc etc.

I am more of a front end designer and am unsure how to do this. Will this require custom SQL?

Any help or advice would be very much appreciated.

Thanks!

1 Answer 1

0

Unfortunately there is no creation date associated with a category, so you have to infer what is the newest by virtue of it having a higher ID. IDs start at 1 and ascend, so newer categories will have higher IDs. With that in mind, we can query for 1 category, with parent equal to 0 (no parent, or top level category only), ordered by ID descending. That will give us 1 top-level category with the highest ID, which should be the newest parent category.

$args = array(
    'orderby' => 'id',
    'order'   => 'DESC',
    'number'  => 1,
    'parent'  => 0,
);
$newest_parent = get_terms( 'category', $args );

You can then use that term in a WP_Query to fetch the articles-

$articles = new WP_Query(
    array(
        'cat' => $newest_parent[0]->term_id,
        'posts_per_page' => -1
    )
);

Not the answer you're looking for? Browse other questions tagged or ask your own question.