Vlad Ivanov Vlad Ivanov - 6 days ago 6
PHP Question

How can I add own theme template for custom post type?

I have some post type, but now I need to add certain templates like in pages section.

function products_init() {
$args = array(
'label' => 'Products',
'capability_type' => 'page',
'menu_icon' => 'dashicons-cart',
'taxonomies' => array('category'),
'rewrite' => array('slug' => 'products'),
'hierarchical' => false,
'public' => true,
'show_ui' => true,
'menu_position' => 4,
'can_export' => true,
'has_archive' => true,
'exclude_from_search' => false,
'publicly_queryable' => true,
'query_var' => true,
'supports' => array('title', 'editor', 'thumbnail', 'page-attributes')
);
register_post_type('products', $args);
}
add_action('init', 'products_init');

Answer

As the codex mentioned, you need to add two files to display custom post type.

archive-{post_type}.php
single-{post_type}.php

If you got a 404 error, you could try to call flush_rewrite_rules() in functions.php and refresh your page. If everything is ok, remove flush_rewrite_rules() immediately.

Otherwise you could flush reweire rules from dashboard -> Settings->Permalink page. Click on save button and then check if you can see the page. Save permalink settings will also call flush_rewrite_rules().