在 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> |
<!-- 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> |
<!-- 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
来源:
https://www.wpdaxue.com/wordpress-selected-function.html
微信公众号
手机浏览(小程序)
Warning: get_headers(): SSL operation failed with code 1. OpenSSL Error messages:
error:14090086:SSL routines:ssl3_get_server_certificate:certificate verify failed in
/mydata/web/wwwshanhubei/web/wp-content/themes/shanhuke/single.php on line
57
Warning: get_headers(): Failed to enable crypto in
/mydata/web/wwwshanhubei/web/wp-content/themes/shanhuke/single.php on line
57
Warning: get_headers(https://static.shanhubei.com/qrcode/qrcode_viewid_32238.jpg): failed to open stream: operation failed in
/mydata/web/wwwshanhubei/web/wp-content/themes/shanhuke/single.php on line
57