善用 WordPress 选择函数 selected()

在 WordPress 开发的过程中,我们需要使用到各种 WordPress 函数,今天介绍一个非常简单实用的选择函数 selected() ,它可以简化我们制作一个多项选择列表的代码量。

按照常规方法,要制作一个下拉选择列表,我们通常要使用 if() 函数进行判断:

<!-- Testing the values with if() -->
<select name="options[foo]">
    <option value="1" <?php if ( $options['foo'] == 1 ) echo 'selected="selected"'; ?>>1</option>
    <option value="2" <?php if ( $options['foo'] == 2 ) echo 'selected="selected"'; ?>>2</option>
    <option value="3" <?php if ( $options['foo'] == 3 ) echo 'selected="selected"'; ?>>3</option>
</select>

如果我们采用 selected() 函数,实现同样功能的代码就简单了很多:

<!-- Using selected() instead -->
<select name="options[foo]">
    <option value="1" <?php selected( $options['foo'], 1 ); ?>>1</option>
    <option value="2" <?php selected( $options['foo'], 2 ); ?>>2</option>
    <option value="3" <?php selected( $options['foo'], 3 ); ?>>3</option>
</select>

要了解 selected() 函数,请访问 http://codex.wordpress.org/Function_Reference/selected