Last active
December 15, 2023 12:51
-
-
Save diggeddy/41bcabfcf1771c2890d22337f58b05f9 to your computer and use it in GitHub Desktop.
custom archive links for categories by year
This file contains hidden or 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
// generate custom archive links for current category by year | |
function get_category_archive_links_by_year($cat_id) { | |
global $wpdb; | |
// Get years with posts in the current category along with post count | |
$years_with_count = $wpdb->get_results( | |
"SELECT YEAR(post_date) AS year, COUNT(ID) AS post_count | |
FROM $wpdb->posts | |
INNER JOIN $wpdb->term_relationships ON ($wpdb->posts.ID = $wpdb->term_relationships.object_id) | |
INNER JOIN $wpdb->term_taxonomy ON ($wpdb->term_relationships.term_taxonomy_id = $wpdb->term_taxonomy.term_taxonomy_id) | |
WHERE $wpdb->term_taxonomy.taxonomy = 'category' | |
AND $wpdb->term_taxonomy.term_id = $cat_id | |
AND post_type = 'post' | |
AND post_status = 'publish' | |
GROUP BY YEAR(post_date) | |
ORDER BY post_date DESC" | |
); | |
$links_with_count = array(); | |
foreach ($years_with_count as $data) { | |
$year_link = get_category_link($cat_id) . '?year=' . $data->year . '&category_name=' . get_category($cat_id)->slug; | |
$links_with_count[] = '<a href="' . esc_url($year_link) . '">' . $data->year . ' (' . $data->post_count . ' posts)</a>'; | |
} | |
return $links_with_count; | |
} | |
function display_current_category_year_archives_shortcode() { | |
$cat_id = get_queried_object_id(); | |
$category_archive_links_with_count = get_category_archive_links_by_year($cat_id); | |
if ($category_archive_links_with_count) { | |
$output = '<h2>Posts by Year</h2>'; | |
$output .= '<ul>'; | |
foreach ($category_archive_links_with_count as $link) { | |
$output .= '<li>' . $link . '</li>'; | |
} | |
$output .= '</ul>'; | |
return $output; | |
} | |
return ''; | |
} | |
add_shortcode('category_year_archives', 'display_current_category_year_archives_shortcode'); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Create a shortcode:
[category_year_archives]
that will return a list of category by year archive links.