我正在使用主题选项。网页中的php文件:http://themeshaper.com/2010/06/03/sample-theme-options/
我可以成功地添加新的下拉选项,但是,当我添加新的文本输入时,当我在管理区域(我添加了THEME\\u目录)查看它时,我会收到此错误:
<br /> <b>Notice</b>: Undefined index: cpt_sm_dribbble_handle in <b>/[THEME_DIRECTORY]/theme-options.php</b> on line <b>359</b><br />
当我将输入值更改为其他值并保存时,它工作正常,不再出现错误。但是,我不希望用户看到此错误消息。我宁愿它只是显示空白,因为还没有输入值。
我怀疑我收到此错误是因为数据库无法识别此新选项。我想我需要在代码中进行某种验证,以说明如果不存在,请将值设置为null。虽然我不确定这是否真的是问题所在,如果是,如何解决它。
下面是我的选项文件和一个新的文本选项的最小化代码(我注意到了引发错误的那行代码):
add_action(\'admin_init\', \'cpt_options_init\');
add_action(\'admin_menu\', \'theme_options_add_page\');
function cpt_options_init() {
register_setting(\'cpt_options\', \'cpt_theme_options\', \'theme_options_validate\');
}
function theme_options_add_page() {
add_theme_page(\'Theme Options\', \'Theme Options\', \'edit_theme_options\', \'theme_options\', \'theme_options_do_page\');
}
function theme_options_do_page() {
global $sm_select_options;
if (!isset($_REQUEST[\'settings-updated\']))
$_REQUEST[\'settings-updated\'] = false;
?>
<form method="post" action="options.php">
<?php settings_fields(\'cpt_options\'); ?>
<?php $options = get_option(\'cpt_theme_options\'); ?>
<tr valign="top">
<th scope="row">Dribbble</th>
<td>
<label class="description" for="cpt_theme_options[cpt_sm_dribbble_handle]">Dribbble Username</label>
<input id="cpt_theme_options[cpt_sm_dribbble_handle]" class="regular-text" type="text" name="cpt_theme_options[cpt_sm_dribbble_handle]" value="<?php esc_attr_e($options[\'cpt_sm_dribbble_handle\']); ?>" /> // THIS IS THE LINE THAT IS THROWING THE ERROR (line 359)
</td>
</tr>
</form>
<?php
}
function theme_options_validate($input) {
global $sm_select_options;
// Say our text option must be safe text with no HTML tags
$input[\'cpt_sm_dribbble_feed\'] = wp_filter_nohtml_kses($input[\'cpt_sm_dribbble_feed\']);
return $input;
}
你知道我做错了什么吗?
谢谢你的时间。
最合适的回答,由SO网友:Chip Bennett 整理而成
将呼叫包装在isset()
此行中的条件:
<input id="cpt_theme_options[cpt_sm_dribbble_handle]" class="regular-text" type="text" name="cpt_theme_options[cpt_sm_dribbble_handle]" value="<?php esc_attr_e($options[\'cpt_sm_dribbble_handle\']); ?>" />
尝试以下操作:
$cpt_sm_dribbble_handle = ( isset( $options[\'cpt_sm_dribbble_handle\']) ? $options[\'cpt_sm_dribbble_handle\']) : \'\' );
<input id="cpt_theme_options[cpt_sm_dribbble_handle]" class="regular-text" type="text" name="cpt_theme_options[cpt_sm_dribbble_handle]" value="<?php esc_attr_e($cpt_sm_dribbble_handle); ?>" />
EDIT
注意:另一种选择是在init上设置默认选项,以便将此选项设置为某个默认值,例如空字符串。