Wordpress single post content class customization with if-else function

Code Review Asked by Sniffles on August 27, 2020

I have the following code, which displays the content for my custom page template "landingpage.php" and for single posts. The site is based on Bootstrap 4.

<?php if(is_page_template( 'landingpage.php' )): ?>

    <div id="content" class="site-content">
        <div class="container-fluid">
            <div class="row">

        <?php elseif (is_single()): ?>

    <div id="content" class="site-content pt-4">
        <div class="container-fluid">
            <div class="row">

        <?php else: ?>

    <div id="content" class="site-content">
        <div class="container">
            <div class="row">
<?php endif; ?>

I’m wondering if there’s a more elegant and/or shorter code to do this?

One Answer

The third <div> appears to be the same in all three cases, so that can be abstracted out of the cases.

The outermost <div> appears to have class pt-4 applied only if is_page_template( 'landingpage.php' ) returns a value that evaluates to FALSE and is_single() returns a value that evaluates to TRUE.

And the first nested (i.e. second) <div> has class container-fluid if either of those functions return a value that evaluates to TRUE.

This logic could be rewritten as below. I know it strays away from the familiar wordpress style of using the Alternative syntax for control structures and uses the shortcut syntax (i.e. <?=) of echo but it does add some separation of the logic from the markup

// default class names
$contentClass = 'site-content';
$containerClass = 'container-fluid';
if (!is_page_template( 'landingpage.php' )) {
    if (is_single()) {
        $contentClass .= ' pt-4';
    else {
        $containerClass = 'container';
    <div id="content" class="<?= $contentClass; ?>">
        <div class="<?= $containerClass; ?>">
            <div class="row">

It could be simplified using ternary operators but some may argue that would detract from readability.

  • Is this shorter?

    yes, only by two lines

  • is this more elegant?

    Well, that is subjective. The code above should be simpler to read. Consider the scenario where the code is updated by multiple people, including programmers and designers. The programmers can have designers update the markup without affecting the business logic. For more on this topic, refer to Mixing PHP and HTML.

Correct answer by Sᴀᴍ Onᴇᴌᴀ on August 27, 2020

Add your own answers!

Ask a Question

Get help from others!

© 2024 All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP