close

Shelley Bassett

Menu

Close

Adding a Custom Post Type


April 30, 2018

Adding a custom post type can be a daunting experience. But once you understand what components are needed, it's a really simple task.

I use custom post types throughout most websites I build. Adding a custom post type gives more control as to what is featured on a website, rather than being locked into the “blog” format. The most common use of a  custom post type is adding products, but it could really be used for anything. You can see them in action with my portfolio.

Without a plugin, adding a custom post type requires just a little bit of code. This can either be added to the themes functions.php  file, or in a custom plugin. Creating your own plugin is often advised because it allows the data to be transferred across themes.

The WordPress codex has in-depth documentation for creating custom post types. Make sure the hook is called in a function on 'init' . This will ensure your taxonomy always exists when you want to use it. The best practices for adding a custom post type look like this:

This code adds the “products” posts, using the existing categories from the normal blog posts. To learn how to add a custom taxonomy with a custom post type, view the tutorial here.

Customising the code

Custom posts are normally found at your-url.com/custom-post-type/post-title . This is defined in $args  at  'rewrite' => array('slug' => 'products', 'with_front' => false, 'pages' => true), . Changing the slug will change the part before the post-title. You can also use additional code or plugins to rename these urls to include the taxonomy instead. If 'hierarchical' => true, is defined, the category slug will be included in the url. To change the archive being used, change the taxonomy in 'has_archive' => 'category', .

Creating a custom post type is really simple when you understand what goes into the function. Be sure to check that all the $labels and $args  are correct for your names, and then you can easily call the posts on any page you want. Don’t forget, you can create as many custom post types as you need. Just make sure that name of each is unique. It might also be useful to include an identifier in the name to avoid interaction with other plugins.

Leave a comment

Advertisement

Leave a Message | No comments yet

Leave a Reply

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