我已经在主题选项页面上实现了Iris颜色选择器,但是单击“save”并不会保存所选的值,它只是重置为空白(或预置值)。我在这里错过了什么?
functions.php:
function accelerator_admin_scripts(){
wp_enqueue_script( 'custom-js', get_template_directory_uri() . '/js/custom.js', array('jquery'), '1.0.0', true );
wp_enqueue_style( 'wp-color-picker' );
wp_enqueue_script( 'iris', admin_url( 'js/iris.min.js' ), array( 'jquery-ui-draggable', 'jquery-ui-slider', 'jquery-touch-punch' ), false, 1 );
wp_enqueue_script('wp-color-picker', admin_url( 'js/color-picker.min.js' ), array( 'iris' ), false, 1 );
}
add_action('admin_enqueue_scripts','accelerator_admin_scripts');options.php:
function add_theme_menu_item()
{
add_menu_page("Theme Options", "Theme Options", "manage_options", "theme-options", "theme_settings_page", null, 99);
}
add_action("admin_menu", "add_theme_menu_item");
function theme_settings_page(){
?>
Theme Options
';
?>custom.js:
jQuery(document).ready(function($){
$('#color-picker').iris({
hide: true,
palettes: true,
change: function(event, ui) {
// event = standard jQuery event, produced by whichever control was changed.
// ui = standard jQuery UI object, with a color member containing a Color.js object
// change the preview box color
$("#color-box").css( 'background-color', ui.color.toString());
}
});
});
保存后:

在header.php中:
$main_color = get_option('primary_color');返回空白。
发布于 2020-09-21 17:25:32
所以您已经使用了改正了,但是正如注释中指出的,代码中的主要问题是颜色输入没有使用在调用register_setting()时定义的正确名称。
也就是说,第二个参数(数据库选项名)是输入的name属性中应该使用的名称。
// The option name is primary_color:
register_setting("section", "primary_color"); // BTW, "section" is a too generic name..
// So use that in the name:实际上还有另一个问题:颜色输入的值总是#000000,因为它在HTML中是静态设置的,或者没有显示保存在数据库中的值。
因此,要解决这个问题,可以使用get_option()获取保存的值并将其回显到输入中。例如。
wp-color-picker,那么只需将iris设置为自定义JS脚本的依赖项--不需要对wp-color-picker样式进行排队: function accelerator_admin_scripts() { wp_enqueue_script(‘定制-js’,get_template_directory_uri() )。'/js/ custom.js ',//添加iris作为custom.js的依赖项。数组( 'jquery','iris‘),'1.0.0',true );}wp-color-picker样式排队,并将wp-color-picker设置为脚本的依赖项:函数accelerator_admin_scripts() { wp_enqueue_style(‘wp style’);wp_enqueue_script(‘定制-js’,get_template_directory_uri()。'/js/ custom.js ',//添加wp-色选择器作为custom.js的依赖项。数组( 'jquery',‘wp-color- script’),'1.0.0',true );}然后在您的JS脚本中,使用$( '#color-picker' ).wpColorPicker()代替$( '#color-picker' ).iris()。add_settings_section()的调用,但我认为您的实际代码有此调用吗?通常,最好先调用register_setting(),然后调用add_settings_section(),然后调用add_settings_field()。:)https://wordpress.stackexchange.com/questions/375134
复制相似问题