On a recent modification to an existing site I was asked to create a gallery section where the site admin could upload images

As usual, I turned to the ever so adaptable plugin Advanced Custom Fields (ACF) with it’s very versatile gallery field, along with a custom post type (CPT) to hold the photos in. On the front end I had isotope filters working on my archives-photos.php file which was also showing all posts from our CPT.

I had a problem though with creating a list of years for our filters as the function wp_get_archives is very limited in the amount of control you have on it’s HTML output and I needed to create a list similar to the one below with a data-filter attribute in order for the isotope filters to actually work in sorting the list of galleries.

<ul class="project-filter" id="project-filter">
    <li>Filter: </li>
    <li class="active" data-filter="*">All Years</li>
    <li data-filter=".2016">2016</li>
    <li data-filter=".2014">2014</li>
    <li data-filter=".2012">2012</li>
    <li data-filter=".2011">2011</li>
    <li data-filter=".2010">2010</li>

The solution came from a wpbeginner.com article which had a snippet of code to run a custom query against the WordPress database to extract all the years for our CPT. I modified their code slightly as their’s was outputting months as well, grouping them into years, where as al I wanted was the year. The final code is below. I hope it helps someone else trying to modify the output of wp_get_archives.

<ul id="project-filter" class="project-filter">
    <li>Filter: </li>
	<li data-filter="*" class="active">All Years</li>
global $wpdb;
$limit = 0;
$year_prev = null;
$years = $wpdb->get_results("SELECT DISTINCT YEAR( post_date ) AS year FROM $wpdb->posts WHERE post_status = 'publish' and post_date <= now() and post_type = 'photos' ORDER BY post_date DESC");
foreach($years as $year) : ?>
    <li data-filter=".<?php echo $year->year; ?>"><?php echo $year->year; ?></li>
<?php endforeach; ?>