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?
best regards
Don't over-complicate this by trying to add styles via PHP. Add the ID via PHP...but not the styles themselves.
Since you only apply the boxed
ID when the boxed layout is in effect, you can simply define some #boxed
CSS styles. These styles will ONLY be applied if the ID exists in your markup...which means they won't come into effect when the ID isn't applied by your PHP.
In other words, put this in your CSS stylesheet, and forget about it:
#boxed {
width: 999px;
}
A flexible option would be to use the body_class()
function to add an additional class to your body tag. This would allow you to scope your styles accordingly:
.boxed section { /* Styles here / } .full-width section { / Styles here */ }
By adding the class on the body you can effectively target everything. This way you're keeping your styles separate from your markup.
Another option would be to keep your universal styles in one stylesheet and then load an additional stylesheet for your full-width/boxed specific styles. This can be handy for organisational purposes, by does add an extra http request, so you'd need to consider bear that in mind.