Custom Post Type Templates

We use custom post types a lot when we build WordPress sites for clients.  With very little setup, we get a bunch of functionality that makes our clients lives easier when they are adding content for any type of article or even a list. For example, if a client has a bunch of employees they want displayed on the website, many times it is very difficult to manage this list within the page editor.  The html can very easily get messed up when trying to separate the list or add things like images for each person.  This is where custom post types come in.  When we create a custom post type, WordPress sets up a new menu item, giving us all the add/edit/delete richness of pages and posts for free.  We would add something like this to the functions.php for the theme are building for the client:

register_post_type( 'employees',
 array( 
    'label' => __('employees'), 
    'show_ui' => true,
    'menu_position' => 6, 
    'public' => true,
    'has_archive' => true,
    'supports' => array(
    'title',
    'editor',
    'thumbnail',
    'revisions',
    'page-attributes')
   ) 
 );
}
add_action('init', 'profile_type');

See the WordPress documentation for more information.  The one thing that has tripped us up is trying to get custom post types working with your existing templates.  If you want to use the single.php template and the archive.php template from your theme for your new custom post type, the key attributes are “public” and “has_archive”. Public set to true shows your single posts using the single.php template and has_archive set to true will show your archive.php.  When you add a new custom post type to your functions.php, you may need to run flush_rewrite_rules(), or simply just re-save your Permalinks under Settings.

logo

View other articles in: Code