2

I'm using this nifty little plugin called Custom Post Type UI to add custom post types to my WordPress site and am having a little trouble working out the best way to apply a page template to my custom post types.

Does anyone know the best way to achieve this?

Any help is appreciated. Thanks in advance!

4

WordPress has a built-in template hierarchy that determines what template file will be loaded for a given type of post or page. If you have a look at the visual overview of the hierarchy, you'll find that custom posts have their own specific entries. For example, if your custom post type is named book, then a single post's template will be single-book.php if it exists, single.php if it does not. (index.php is the global fallback -- a theme really only needs to contain style.css and index.php to function.)

Any desired template files (ie, single-{$posttype}.php) should be added to your active theme.

References

  • Ok, so let's take your example. Let's say we have a custom post type called "book". A file called single-book.php controls is my template for any singular "book" pages while archive-book.php is my template for the archive of my custom post type "book"? This works for "single-book.php", I can edit this template fine. But for some reason, it doesn't work for "archive-book.php". Any reason why? – realph Dec 30 '13 at 0:45
  • 1
    @realph are you sure that the CPT is registered with has_archive set to true? – gmazzap Dec 30 '13 at 1:03
  • @G.M.You are the best! Thanks for that, should do a bit more searching next time. Working perfectly now! – realph Dec 30 '13 at 1:07
  • Sorry, one last question: So is using the template hierarchy the correct way to go about setting up templates for your custom post types? – realph Dec 30 '13 at 1:08
  • 1
    The template hierarchy is essentially a flowchart that tells you what files WordPress will try to use to display a given post/page/archive/taxonomy/etc. It will use the left-most file that it finds. If all else fails it will use index.php. – Pat J Dec 30 '13 at 2:34

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.