Skip to content

Instantly share code, notes, and snippets.

@mahfuzul
Last active January 26, 2016 07:33
Show Gist options
  • Save mahfuzul/e66a28f7ee104d4159ef to your computer and use it in GitHub Desktop.
Save mahfuzul/e66a28f7ee104d4159ef to your computer and use it in GitHub Desktop.
Get Unique years from post type
<?php
/**
* Get posts year
* @return [type] [description]
*/
function get_post_years() {
global $wpdb;
$sql = "SELECT YEAR(STR_TO_DATE(p.post_date, '%Y')) as year
FROM $wpdb->posts as p
WHERE p.post_type = 'post' AND p.post_status = 'publish'
GROUP BY year
ORDER BY year DESC";
return $wpdb->get_col($sql);
}
?>
<?php
// Templates
$years = get_post_years();
if (count($years)) : ?>
<ul>
<?php foreach ( $years as $year ): ?>
<li><a href="<?php echo home_url('/') . $year; ?> " title=""><?php print $year; ?></a></li>
<?php endforeach ?>
</ul>
<?php endif; ?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment