Skip to content

Instantly share code, notes, and snippets.

@sachyya
Created October 29, 2015 11:13
Show Gist options
  • Save sachyya/aae2bb92313fe2983b40 to your computer and use it in GitHub Desktop.
Save sachyya/aae2bb92313fe2983b40 to your computer and use it in GitHub Desktop.
This gist is to loop the posts in a specific year in a chunk by year.
//create two custom functions
<?php //retrive years that have posts
function st_get_years_having_posts( $post_type ) {
// get years that have posts
global $wpdb;
$date_query = "SELECT YEAR(post_date) AS year FROM {$wpdb->prefix}posts WHERE post_type = '{$post_type}' AND post_status = 'publish' GROUP BY year DESC";
$years = $wpdb->get_results( $date_query );
return $years;
}
// get post data by year
function st_posts_this_year( $post_type, $year ){
global $wpdb;
$press_query = "SELECT * FROM {$wpdb->prefix}posts WHERE post_type = '{$post_type}' AND post_status = 'publish' AND YEAR(post_date) = '" . $year . "'" ;
// get posts for each year
$posts_this_year = $wpdb->get_results( $press_query );
return $posts_this_year;
}?>
//implement like this
<?php $years = st_get_years_having_posts('press'); //st_get_years_having_posts($post_type);
foreach ( $years as $year ) {
$year = $year->year;
$posts_this_year = st_posts_this_year( 'press', $year );?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment