我正在尝试建立一个简单的插件,但这个设置API并没有让我休息一下。
我在设置页面中注册了一个字段,但我们输入的值不会保存到数据库中。
这是迄今为止我整理的代码。非常感谢您的帮助
<?php
if(is_admin()){
add_action( \'admin_menu\', \'my_plugin_menu\' );
add_action( \'admin_init\', \'register_mysettings\' );
}
function register_mysettings() {
register_setting( \'purchase-history-grid\', \'num_of_columns\' );
add_settings_section(
\'plugin_section\',
__( \'The Grid\', \'wordpress\' ),
\'settings_section_callback\',
\'purchase-history-grid\'
);
add_settings_field(
\'num_of_columns\',
\'Number of Columns\',
\'show_num_of_cols\',
\'purchase-history-grid\',
\'plugin_section\'
);
}
function my_plugin_menu() {
add_options_page( \'Purchase History Grid\', \'Purchase History Grid\', \'manage_options\', \'purchase-history-grid\', \'my_plugin_options\' );
}
function my_plugin_options() {
if ( !current_user_can( \'manage_options\' ) ) {
wp_die( __( \'You do not have sufficient permissions to access this page.\' ) );
}
?>
<div class="wrap">
<h2>Purchase History Grid by SolutionsW3</h2>
<form method="post" action="options.php">
<?php
settings_fields( \'purchase-history-grid\' );
do_settings_sections( \'purchase-history-grid\' );
submit_button();
?>
</form>
</div>
<?php
}
function show_num_of_cols() {
// get the value of the setting we\'ve registered with register_setting()
$setting = get_option(\'num_of_cols\');
// output the field
?>
<input type="text" id="num_of_cols" name="num_of_cols" value="<?php echo isset( $setting ) ? esc_attr( $setting ) : \'\'; ?>">
<?php
}
function settings_section_callback( ) {
echo __( \'Please configure the grid here\', \'wordpress\' );
}
?>
最合适的回答,由SO网友:Sally CJ 整理而成
选项值未保存在数据库中,因为您可以在下面看到,注册的选项名称为num_of_columns
和not num_of_cols
:
// The second parameter is the option name.
register_setting( \'purchase-history-grid\', \'num_of_columns\' );
因此,请确保在设置字段回调中使用正确的选项名称:
使用get_option( \'num_of_columns\' )
检索保存的选项时,以及
使用name="num_of_columns"
在<input>