2

If I'm understanding correctly, I can create a custom template for a specific page by creating a file called page-{my_page_title_or_id), which gets displayed when visiting that page. I can also create a custom template for pages by adding Template Name: My Page Type in the header comments.

However, the situation with posts seems very different. As far as I can tell, creating a file called single-{post_title_or_id) doesn't force display of that file for the given post. It appears to do nothing at all.

I understand that I can create a custom post type and display instances of that with single-{post_type_name}, which is great. However, if I want to create a template for just one particular post, it seems like overkill, and I would have to include conditional logic for when the id/title of the post matched the onle I want to display.

Am I missing something here? Is my understanding of the situation correct? Please can someone tell me the most simple way to display a custom view for a post with a given title/id?

1 Answer 1

7

A) Single Post Templates: single-{post-type}-{post-name}.php

It's informative to check out the get_single_template() function.

There we find the following template possibilities:

"single-{$object->post_type}-{$object->post_name}.php"
"single-{$object->post_type}.php"
"single.php"

In WordPress 4.7 this part will be added:

"single-{$object->post_type}-{$name_decoded}.php"    

So it looks like you forgot the {$object->post_type} part in the template's name.

Example:

The single template name for the post with the slug hello-world:

single-post-hello-world.php

B) Custom Single Post Templates

Another feature in WordPress 4.7 will be the support for custom single post templates.

Check out ticket #18375 for more info.

Example:

I just tested this new feature, by creating a template file, e.g. tpl-wpse-test.php, in the current theme directory:

<?php
/**
 * Template Name:      WPSE Template Test
 * Template Post Type: post
 */
 get_header();
 ?><div id="main"> WPSE Template Test - Success! ;-) </div><?php
 get_footer();

Then the following meta box shows up automatically in the backend for the corresponding post types.

Metabox

There's a multi post type support as well, e.g.:

 * Template Post Type: posttype1, posttype2, posttype3

But there's no need to use add_theme_support(), like we use to get the featured image meta box.

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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