0

With Template Files

I am building a theme that has very few differences between templates. Right now I have it set up more or less like this:

  • singular.php - Single pages/posts; full post content, comments
  • home.php - The blog page; full post content, no comments
  • index.php - Everything else; post excerpts

With Conditional Tags

Looking at this setup, I realized that I could do something like this:

<?php get_header(); ?>

<div id="main-column">

<?php if ( have_posts() ) : while ( have_posts() ) : the_post();

    if ( is_singular() ) :
        get_template_part( 'template-parts/content', 'full' );
        if ( comments_open() || get_comments_number() ) :
            comments_template();
        endif;
    elseif ( is_home() ) :
        get_template_part( 'template-parts/content', 'full' );
    else :
        get_template_part( 'template-parts/content', 'excerpt' );
    endif;

endwhile; else : echo "Nothing here."; endif; ?>

</div> <!-- #main-column -->

<?php
get_sidebar();
get_footer();
?>

I like this method for the same reason I like template parts - code that would have been repeated is now in only one place. If I decide to change the overall structure of the page, I don't have to worry about editing multiple files.

Is there an advantage/disadvantage to only using index.php?

0

Actually, a theme only needs 3 core files to be recognized as a proper theme. These files are:

  • index.php
  • styles.css
  • functions.php

If you have these 3 files in your theme's folder, you are good to go. The point of having multiple template files is to open a way for developers and users to customize their content output. You don't have to do this, but I strongly suggest that you add specific template files at least for the following:

  • 404.php
  • search.php
  • single.php
  • archive.php
  • comments.php
  • page.php

You never know what happens in the future. You might use a hundred conditionals in your index.php file, and then need a single.php tomorrow. Better to be prepared in the first place.

  • But as soon as single.php is added, it would override index.php, even in a child theme. index.php could even be used as a starting point if necessary, cutting out anything not required for single.php. Isn't it simpler to add a more specific template once it is needed than to maintain several template files that differ only slightly? – pladams9 Feb 12 '18 at 4:26
  • As I mentioned, it's totally optional. It depends how sophisticated your theme is, and what plans you have for it in the future. – Jack Johansson Feb 12 '18 at 10:17

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.