0

When you put a name at the top of your index.php like:

<?php
/* Template Name: Blog Template */ 
?>

it will work for front-page and it will also create a new page template. I'm wondering if this is allowed and done on purpose? Are there any pitfalls of using index.php as page template?

1 Answer 1

1

You can use it as a page template, just as any file with such a header can be used.

That doesn't necessarily mean it's a good idea. The template hierarchy already uses index.php as a last resort if it cannot find an appropriate template for a page/post/listing etc, so a specific page will already have template filenames matched to it that will be looked for, e.g. page-{slug}.php or page-{id}.php or page.php etc

Using index.php as a page template potentially muddles up your theme structure by making it dual purpose, and complicates things for any other developers ( who can then point it out and make you look bad to the client ).

The ability to do this is not deliberate. There are no rules as to which files can and cannot be detected as a page template. So long as the file has that header comment it will show up. So header.php can be used, so can footer.php, and you can create a terrible mess doing so, and there's nothing to stop you.

So I would recommend against it, but it is possible.

If you're looking to prevent code duplication, I instead point you to the get_template_part function. You can separate out the common components into separate files and include them, and it'll also handle child themes and subfolders.

2
  • Thanks, I see! It actually makes more sense to me to pack blog into index.php AND give users ability to set more blogs as subpages than to duplicate that code into index.php and template-blog.php. The only difference is actually if(is_page()){ create custom loop } and else - load whatever it returns. It looks elegant to me. Commented Apr 2, 2013 at 14:27
  • Not sure i got what you meant there, if you have code duplication, I recommend that you instead separate the duplicate code into a separate file and use get_template_part, if you're using if else etc to control what gets shown where on a template then you should split it further and use get_template_part Commented Apr 2, 2013 at 15:10

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.