doifeellucky
doifeellucky

Reputation: 25

Display a custom single.twig for specific categories

In timber you can display custom pages, based on page.twig, like page-casestudies.twig, which I'm using to show a list of all posts with a category of 'casestudies'. Just including /casestudies in the URL will render the page. This is default timber functionality and works exactly as I'd expect. I then want to show (for casestudies) a custom single-casestudies.twig, which is based off but different to single.twig (which I use for blog posts) and needs a different layout. I use additional ACF's in the casestudies. I have no idea how I go about this, or if it is even possible, or if there is a better way, such as custom post types. I've seen lots of posts about custom post types, but they only mention a list of posts, and not the actual display of the custom post itself. Thanks in advance.

Upvotes: 0

Views: 555

Answers (1)

Daniel Post
Daniel Post

Reputation: 101

I don't think Timber has this functionality by default, but you could add it yourself to single.php like this:

$context = Timber::get_context();
$context['post'] = new Timber\Post();
$template = has_category('casestudies') ? 'single-casestudies.twig' : 'single.twig';

Timber::render($template, $context);

The $template variable checks if the post contains the category casestudies, and sets the template to either single-casestudies.twig or single.twig.

Upvotes: 2

Related Questions