Reputation: 472
I have an interesting problem that I could use some help resolving.
I have not done a ton of WordPress sites, but I am familiar with it, and very comfortable with PHP.
I need to know if there is a way to grab posts from the most recently created category in WordPress. Obviously, it's pretty easy and straightforward to grab articles from a specific category, and I don't need help there. What I need is to also filter for the most recently created category and only grab the sub-categories and posts that belong to it. I hope this makes sense.
My client has a magazine type thing 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:
...etc.
How can I query only the most recently created category and articles belonging to it?
Upvotes: 0
Views: 79
Reputation: 1481
i think you need to save a date and the term id in options table, then you can search for the closest date and get the term id.
First you ned to use the 'create_term'
hook:
function addDateTerm($tid, $tt_id){
$date = date('l jS \of F Y h:i:s A');
add_option( '_date_term_'.$tid, $date );
}
add_action("create_term", 'addDateTerm', 2, 10);
With this, any time the admin creates a new term, a new set of data is create in the wp_option table
Now you can get that options and search for te closest date and the term id
function find_closest()
{
$tId = get_terms( 'category', array('hide_empty'=> false));
$date = date('l jS \of F Y h:i:s A');
$termArray = array();
foreach ($tId as $term) {
$dates = get_option( '_date_term_'.$term->term_id);
$termArray[$term->term_id] = $dates;
}
foreach($termArray as $k=>$day)
{
$interval[$k] = abs(strtotime($date) - strtotime($day));
}
asort($interval);
$closest = key($interval);
// print_r($termArray);
// print_r($closest);
echo $closest;
}
This function was taken from here and was modificated for this example.
The $closest
variable shows the term id, and with that you can show your posts
Upvotes: 0