Skip to content

Instantly share code, notes, and snippets.

@chrismademe
Created February 12, 2018 13:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save chrismademe/d06863e91973cfbeb570ac0db34c536a to your computer and use it in GitHub Desktop.
Save chrismademe/d06863e91973cfbeb570ac0db34c536a to your computer and use it in GitHub Desktop.
Order posts by year and month
<?php
/**
* Get Posts by Year
*
* Returns an array of posts
* sorted by year and month.
*
* @param string $post_type Post Type
* @param array $options Options array for get_posts()
*/
function get_posts_by_year( $post_type = 'post', $options = array() ) {
// Set Default options
$defaults = array(
'post_type' => $post_type,
'posts_per_page' => -1,
'orderby' => 'post_date',
'order' => 'DESC'
);
// Merge options with defaults
$options = array_merge($defaults, $options);
// Get posts
$the_posts = get_posts($options);
// False if no posts
if ( !$the_posts )
return false;
// Sort posts
foreach ( $the_posts as $p ) {
$timestamp = strtotime($p->post_date);
$year = date('Y', $timestamp);
$month = date('n', $timestamp);
$sorted[$year][$month][] = $p;
}
// Done!
return $sorted;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment