Reputation: 3
I'm tyring to build a Wordpress theme where user can choose some available options.
Let's say I have an option where user can choose column width from available options. In my page.php, I'm using this code to add class
<div class="<?php if ( my_column_width == '1' ) : ?> full-width
<?php elseif ( my_column_width == '2' ) : ?> one-two
<?php elseif ( my_column_width == '3' ) : ?> one-three">
Usually I put it in a single line, above code just for it' easier to understand. I have a lot of options on my theme, so those conditional statements really make it hard to read my code.
Can someone tell me the better approach to do this? I'm hoping that people who will use my theme can understand the logic when they read my code.
Upvotes: 0
Views: 375
Reputation: 5119
In Wordpress you have several action hooks and filters. In this case, you can use the "body_class" filter. Just see the following example.
add_filter('body_class', 'my_body_classes_function');
function my_body_classes_function( $classes, $col_width = 0 ) {
// your settings here
switch ($col_width) {
case 1 :
$classes[] = 'my_col1_class';
break;
default :
$classes[] = 'my_default_class';
break;
}
return $classes;
}
Add this function to your theme 's functions.php and add the following HTML code to your template.
<body <?php body_class(); ?>>
You should also have a look at the wordpress function reference: http://codex.wordpress.org/Function_Reference/body_class#Add_Classes_By_Filters
Upvotes: 0
Reputation: 3390
Create a function:
function get_my_option_class($width)
{
switch ($witdh) {
case 2:
$class = 'one-two';
break;
case 3:
$class = 'one-three';
break;
case 1:
default:
$class = 'full-width';
}
return $class;
}
And then you'll do this:
<div class="<?= get_my_option_class($my_column_width) ?>">
Functions are reusable and much better than hard-coding any logic in your templates. If this code is supposed to run on PHP lower than PHP 5.4, then it's better to change the last line to this:
<div class="<?php echo get_my_option_class($my_column_width) ?>">
This will work in PHP < 5.4 even if short_open_tag
is off.
Upvotes: 1
Reputation: 27092
Ideal is to have a switch
where you prepare your class and then put this class to your code.
<?php
switch ($my_col_width) {
case 1:
$class = 'full-width';
break;
case 2:
$class = 'two-cols';
break;
case 3:
$class = 'three-cols';
break;
default:
$class = 'four-cols';
break;
}
?>
<div class="<?php echo $class; ?>">text</div>
Second, one-line variant, is
<div class="box-<?php echo $my_col_width; ?>">text</div>
Upvotes: 0