Skip to content

Instantly share code, notes, and snippets.

@vanpariyar
Last active June 24, 2020 05:03
Show Gist options
  • Save vanpariyar/69041dbaf1967d6933c1baa162b060dc to your computer and use it in GitHub Desktop.
Save vanpariyar/69041dbaf1967d6933c1baa162b060dc to your computer and use it in GitHub Desktop.
How to get custom post type archive year in array format with cache support in WordPress ? ( Ported from the WordPress core )
<?php
/**
* @see the function ported from the WP core.
* @see wp_get_archives() functions for more.
*
* @author Ronak Vanpariya
*
* @param are Optional
*
* @return { array } of the object which having 'years' and 'posts' props.
* using caching for the reducing database Load.
*/
function get_archive_years_bypost( $post_type = 'financials' , $limit = '' ) {
global $wpdb ,$wp_locale;
$last_changed = wp_cache_get_last_changed( 'posts' );
$query = "SELECT YEAR(post_date) AS `year`, count(ID) as posts FROM $wpdb->posts $join WHERE post_type = '$post_type' AND post_status = 'publish' GROUP BY YEAR(post_date) ORDER BY post_date DESC $limit";
$key = md5( $query );
$key = "wp_get_archives:$key:$last_changed";
$results = wp_cache_get( $key, 'posts' );
if ( ! $results ) {
$results = $wpdb->get_results( $query );
wp_cache_set( $key, $results, 'posts' );
}
return $results;
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment