jayminkapish - Jaymin Patel, Wordpress Developer, New York
Subscribe to jayminkapish RSS Friend Jaymin Patel on Facebook Follow Jaymin Patel on Twitter

« Go to home page

Date archive for a category

There are a few ideas out there How to build date archive for a category. I am joining the race now.

Some of us, wordpress developers, may think this is hacky but I bet a few will like it this way because this works!.

This idea would end up in url like this

/archives/category/{category-slug}/yyyy/mm/

Lets get started and you can Download code here and you can put that in your active theme’s functions.php file.

I am going to use init hook.

add_action('init','my_date_archive_for_category');

We can check if incoming request contains /archives/category/ inside my_date_archive_for_category function. If it does, this is our category/date archive page.

Now breakup incoming request, and check every part of the request. We need category slug, year and month in place.

$request_parts = explode('/', $request);

Parts of request

Array ( [0] => [1] => archives [2] => category [3] => category-slug [4] => yyyy [5] => mm [6] => )

Here, we need to validate a few parts of the request like category slug, yyyy and mm.

$category_array = get_term_by('slug', $request_parts["3"], "category", ARRAY_A);

Now time to query wordpress.

query_posts(array('cat'=>$category_array["term_id"], 'year'=>$request_parts["4"], 'monthnum'=>$request_parts["5"]));

If we have posts, display them otherwise set a flag which we can use later to show 404 so visitors do not get confused.


if ( have_posts() ) : while ( have_posts() ) : the_post();
........
endwhile;
else:
$is404 = true; /* set the flag so we know no posts found and display 404. */
endif;

DO NOT FORGET to put

exit;

at the end.

Putting exit at the end will end further PHP execution on your blog.

Do not forget to let me know how this works on your blog.


10 Responses


Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>


About

Wordpress Work

Plugins I like

Recent Posts

Wordpress News

Blogroll

Connect

I am excited about