Custom Post Type Archives Part 2

The previous post covered how to get the posts by year and month in the URL. This post will cover how to get links to show up in the sidebar, just like they do with normal posts and the Archive Widget.

Logically, the easiest method will be to copy the Archive Widget and modify it. The plugin has a wp_get_post_type_archives function which is a wrapper for the WordPress wp_get_archives function and will work for custom post types.

Creating the Widget

The widget is located in wp-includes/default-widgets.php. I copied the whole class over to my own functions.php file and modified the names so I would have a unique widget. Since this widget would show sermon archives, it’s called widget_sermon_archive. I inserted the word ‘sermon’ in other places which originally referred to widget_archives.

Remember to register the widget.

add_action('widgets_init', create_function('','return register_widget("WP_Widget_Sermon_Archives");'));

Calling the Plugin’s function

Next, just modify the function calls from wp_get_archives() to wp_get_post_type_archives.

This function takes an additional argument which specifies the post type. I just used ‘sermon’ as my argument.

Modify wp_get_post_type_archives()

Unfortunately, the previous bit of code isn’t good enough. WordPress multisite appends the blog/ slug to posts, and this is what comes back from the built in function. The fix is simple but because there’s no way to customize the function, I had to copy the whole thing over to my own file and call it from the widget. What has to be done is to change the $pattern variable to include the blog/ slug.

Using the Widget

Now, just go to Appearance -> Widgets in the menu and drag new the Sermon Archives widget over to the sidebar!

Custom Post Type Archives Part 3

Advertisements

2 thoughts on “Custom Post Type Archives Part 2”

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s