How to Create a Custom Post Types Archive Page in WordPress

157

Custom Post Types was one of the awesome features included in WordPress 3.0. One of our users asked us a question on twitter, how to create a custom post types archive page. We covered it in our initial article about Custom Post Types, but it wasn’t explained thoroughly. In this article, we will show you a step by step guide on how to create a custom post types archive page in WordPress.

First thing you need to make sure is that your custom post type has archive enabled in the code. To do this, you need to go to your custom post type code (can be found in your theme’s functions.php file or site-specific plugin file). You need to make sure that you have has_archive argument set to be true.

An example code would look like this:

  add_action( 'init', 'create_post_type' );  function create_post_type() {  	register_post_type( 'deals',  		array(  			'labels' => array(  				'name' => __( 'Deals' ),  				'singular_name' => __( 'Deal' )  			),  		'public' => true,  		'has_archive' => true,  		)  	);  }

Notice how we have has_archive set to be true in the array. You need to have this in your code. Once you do that, your custom post type will be assigned an archive page which can be accessed by going to a link like this:

http://yoursite.com/deals/

Note: replace deals with whatever is the name of your custom post type.

WordPress by default uses the archive template of your theme to display the custom post type archive page. If you are ok with how the default archive looks, then you are done here. You have successfully created a custom post type archive page for your WordPress site.

However, if you want to create a custom archive page for your custom post type, then you would need to create a new file called archive-{posttype}.php. In our example, the file name would be archive-deals.php

The best way to start would be to copy the code from your theme’s archive.php file and paste it in your archive-{posttype}.php file. Then start tweaking from there. You can style this archive file to your heart’s desire. A very basic template would look like this:

  <?php  get_header();  if(have_posts()) : while(have_posts()) : the_post();  	the_title();  	echo '<div class="entry-content">';  	the_content();  	echo '</div>';  endwhile; endif;  get_footer();  ?>

Once you are done upload this file in your theme’s directory. After you have done that, you would see a custom archive page for your custom post type.

There you have it. You should now have a custom post types archive page in WordPress. For those who want to see custom examples, then you can see those by visiting our WordPress coupons page or our WordPress books page.