我有用于不同样式表选择的wordpress主题设置,它是在前端使用if-else语句设置的。
我的wordpress设置可能有以下值池中的一个值
red ,green, blue, yellow, white, pink, black, grey ,silver or purple
我的模板:
<link href="<?php bloginfo("template_url"); ?>/style.css" rel="stylesheet" media="all" />
<?php if (get_option('my_style') == "red" : ?>
<link href="<?php bloginfo("template_url"); ?>/css/red.css" rel="stylesheet" media="all" />
<?php endif; ?>
<?php if (get_option('my_style') == "green" : ?>
<link href="<?php bloginfo("template_url"); ?>/css/green.css" rel="stylesheet" media="all" />
<?php endif; ?>
<?php if (get_option('my_style') == "blue" : ?>
<link href="<?php bloginfo("template_url"); ?>/css/blue.css" rel="stylesheet" media="all" />
<?php endif; ?>
<?php if (get_option('my_style') == "yellow" : ?>
<link href="<?php bloginfo("template_url"); ?>/css/yellow.css" rel="stylesheet" media="all" />
<?php endif; ?>
.
.
.
.
.
<?php if (get_option('my_style') == "purple" : ?>
<link href="<?php bloginfo("template_url"); ?>/css/purple.css" rel="stylesheet" media="all" />
<?php endif; ?>
通过这种方式,我可以根据需要获得特定的样式表。但是,如果选项池中有更多的值,这个php代码就会变得很长。那么,有没有什么方法可以使用数组来缩短这个时间呢?
您可以将其简化为
<link href="<?php bloginfo("template_url"); ?>/css/<?php echo get_option('my_style'); ?>.css" rel="stylesheet" media="all" />
如果函数get_option
返回的字符串和css文件的名称相同,我认为您不需要数组。
此选项:
<?php
$arraystyle=array("red", "green", "blue", "yellow", "white", "pink", "black", "grey", "silver", "purple");
$val=get_option('my_style');
if(!in_array($val, $arraystyle)){
echo "Style not found";
return false;
}
?>
<link href="<?php bloginfo("template_url"); ?>/css/<?php echo $arraystyle[$val];?>.css" rel="stylesheet" media="all" />
这里没有真正需要使用数组。您正在根据某个值对包含的CSS文件进行更改。
我认为您正在寻找的是一个切换案例命令。这里有一个简单的例子,你可以用它做什么-
<?php
$my_style = get_option('my_style');
switch($my_style){
case "red":
echo '<link href="'. bloginfo("template_url"). '/css/red.css" rel="stylesheet" media="all" />';
break;
case "green":
echo '<link href="'. bloginfo("template_url"). '/css/green.css" rel="stylesheet" media="all" />';
break;
default :
echo '<link href="'. bloginfo("template_url"). '/css/default.css" rel="stylesheet" media="all" />';
break;
}
?>
使用此方法,可以为每个my_style
选项包含多个更改。请注意,使用默认大小写来处理任何意外值。。。
参考-
switch structures
<?php
$my_styles = array(
'red',
'green',
'blue',
'yellow',
'white',
'pink',
'black',
'grey',
'silver'
);
?>
<?php if(in_array($my_style = get_option('my_style'),$my_styles)) : ?>
<link href="<?php echo bloginfo("template_url")."/css/{$my_style}.css"; ?>" rel="stylesheet" media="all" />
<?php endif; ?>
您可以用$my_styles填充变量,并使用所有可用的样式,无论是来自数据库还是其他任何样式。。