Pages

Thursday, December 19, 2013

Create yearly archive listing for custom post type + wordpress - solved


Please write below code in functions.php

function get_cpt_archives( $cpt, $echo = false ) // $cpt = custom post type slug
{
    global $wpdb;
    $sql = $wpdb->prepare("SELECT * FROM $wpdb->posts WHERE post_type = %s AND post_status = 'publish' GROUP BY YEAR(wp_posts.post_date), MONTH(wp_posts.post_date) ORDER BY wp_posts.post_date DESC", $cpt);
    $results = $wpdb->get_results($sql);

    if ( $results )
    {
        $archive = array();
        foreach ($results as $r)
        {
            $year = date('Y', strtotime( $r->post_date ) );
            $month = date('F', strtotime( $r->post_date ) );
            $month_num = date('m', strtotime( $r->post_date ) );
            $link = get_bloginfo('siteurl') . '/corporate/' . $cpt . '/' . $year . '/' . $month_num;
            $this_archive = array( 'month' => $month, 'year' => $year, 'link' => $link );
            array_push( $archive, $this_archive );
        }

        if( !$echo )
            return $archive;
        foreach( $archive as $a )
        {
            echo '<li><a href="' . $a['link'] . '">' . $a['month'] . ' ' . $a['year'] . '</a></li>';
        }
    }
    return false;
}

In sidebar page you have to write below function:

get_cpt_archives('Custom Post Type Slug');

No comments: