• Hello. 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.

    My client needs to add a new category 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?

    Any help would be very much appreciated.

Viewing 1 replies (of 1 total)
  • Hello codeguerrilla,

    we can do this in two steps:

    1. Get the last created category ID
    2. Get posts from this category

    Step 1.

    We use the get_terms function.

    $latest_category_ids = get_terms(
    	'category', // taxonomy name, in our case 'category'
    	array(
    		'orderby' => 'id', // newest records in DB have the highest ID number
    		'order' => 'DESC', // get the latest -> descending ordering
    		'number' => 1, // get only the last one
    		'fields' => 'ids' // get the latest category ID field only, faster a bit :D
    	)
    );
    
    // get_terms returns an array even if there is just a single item in it
    $latest_category_id = $latest_category_ids[0];

    Step 2.

    We use the get_posts function to retrieve some posts from the DB.

    $args = array(
    	'posts_per_page'   => 5, // how many of posts do you want?
    	'category'         => $latest_category_id, // the latest category ID
    	'post_type'        => 'post' //get only posts, not pages etc
    );
    
    $posts_array = get_posts( $args );
Viewing 1 replies (of 1 total)
  • The topic ‘Grab posts from recently created category’ is closed to new replies.