0

I posted this on Stackoverflow and as suggested I am reposting it here if thats ok. Didnt knew there was a Wordpress section of the site :)

I am working on a Wordpress theme and want to give the option to choose between a boxed layout and a full width layout.

For this purpose I created a variable in my header.php:

<head>
    <?php
        $isBoxedLayout = true;
    ?>
...
</head>

Down in the body I am asking if the variable is set:

<?php if($isBoxedLayout) { echo '<div id="boxed">'; } ?>
...
<?php if($isBoxedLayout) { echo '</div>'; } ?>

This works fine so far. But now I also want to change some css styles if this variable is set. My problem is that I am not so good in PHP yet so my solution would be something like this:

<head>
    <?php
        $isBoxedLayout = true;
    ?>
    ...
    if ($isBoxedLayout) {
        echo '<style type="text/css">';
        echo '#container {width:999px;}';
        echo '</style>';
    }
</head>

But I think this is not good programming because my header.php file would soon be full of code and confusing if I would add some other options. So logically I should create a variable or an array maybe in the functions.php file and outsource my code like this:

$isBoxedLayout = true;

if ($isBoxedLayout) {
    function boxed_css_styles() {
        echo '<style type="text/css">';
        echo '#container {width:999px;}';
        echo '</style>';
    }
}

Is my thinking right? And if so how would I access the functions I create in my index.php or header.php or whatever. Or would it work to print the styles in the functions.php?

1 Answer 1

1

Use the function body_class() in your templates:

<body <?php body_class(); ?>>

This creates extra classes on the body element. Then filter its values in your functions.php:

add_filter( 'body_class', function( Array $classes ) {

    if ( $GLOBALS[ 'isBoxedLayout' ] )
        $classes[] = 'isBoxedLayout';

    return $classes;
});

Now you can move all CSS declarations for that to your stylesheet:

.isBoxedLayout #container {
    width:999px;
}

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.