Logic behind the single content template


I’m wondering if I’m understanding the single.php template correctly.

get_template_part('templates/content', 'single');

Refers to content-single.php in /templates/. So if I have a custom post type ‘product’, I have to create a single-product.php with …

get_template_part('templates/content', 'single-product');

Why not having this dynamic logic directly into single.php, by checking if it’s a custom post type and then redirect to the appropriate template file, like …

global $post; 
$single = 'single'; 
if (isset($post->post_type)) $single .= '-' . $post->post_type;
get_template_part('templates/content', $single);

Is it wrong to do something like that ? I don’t really understand the current way of having single.php + multiple single-{$post_type}.php refering to multiple content-single-{$post_type}.php.

Roots is a starter theme, so building on the templates to suit your individual needs, is very much encouraged.

Your solution would work for custom post types but wouldn’t support post formats. Which is best to support? It depends on the end user. Some users will need support for one, both or neither; rather than prescribe this choice, Roots just keeps the templates simple and easy to modify.

The reason for this is that simple code is almost always better:

// Dynamically select single template based on Post Type
<?php get_template_part('templates/content-single', get_post_type()); ?>

// Dynamically select single template base on Post Format
<?php get_template_part('templates/content-single', get_post_format()); ?>
1 Like

Oh ok, I saw the post format logic later on. That makes sense, I’ll use your simpler code based on Post Type, thanks a lot for the explanation !