Created
February 12, 2018 13:17
-
-
Save chrismademe/d06863e91973cfbeb570ac0db34c536a to your computer and use it in GitHub Desktop.
Order posts by year and month
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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