我使用的是在函数中定义的全局变量after_setup_theme
. 此变量未在主题自定义程序中获取更新更改。
Let me explain this with an example:
add_action( \'customize_register\', "example_customizer_register");
function example_customizer_register($wp_customize) {
$wp_customize->add_setting( \'example_settings[example-variable]\', array(
\'type\' => \'option\',
\'default\' => false,
\'sanitize_callback\' => \'esc_attr\'
) );
$wp_customize->add_control( \'example_settings[example-variable]\', array(
\'label\' => \'Example Setting\',
\'type\' => \'checkbox\',
\'section\' => \'title_tagline\',
) );
}
add_action("after_setup_theme", "example_after_setup_theme");
function example_after_setup_theme(){
global $example_settings;
$example_settings = get_option( "example_settings", array());
}
add_action("wp_head", "example_wp_head");
function example_wp_head(){
global $example_settings;
if (isset($example_settings["example-variable"]) && true == $example_settings["example-variable"]) {
echo "Example Setting";
}
}
此代码正在主题自定义程序的站点标识部分添加一个示例设置,但该设置不起作用。如果我改变;
add_action("after_setup_theme", "example_after_setup_theme");
至
add_action("wp", "example_after_setup_theme");
它正在工作。但我需要它
after_setup_theme
. 有什么解决方案吗?
最合适的回答,由SO网友:Thomas Bensmann 整理而成
问题是WP customizer提交了更改,但当时尚未处理这些更改。如果您不能等待WP customizer使用稍后的操作来完成这项工作,那么这里有一个解决方案,您可以获取自定义信息并使用它覆盖我们拥有的信息。
add_action("after_setup_theme", "example_after_setup_theme");
function example_after_setup_theme(){
global $example_settings;
$option_key = "example_settings";
$example_settings = get_option( $option_key, array() );
// Check if wp_customize was posted
if( isset( $_POST[\'wp_customize\'] ) && $_POST[\'wp_customize\'] == "on" && !empty( $_POST[\'customized\'] ) ){
// All the variables we need to look for
$variables_to_find = array(
\'example-variable\'
);
// Get the customized data
$customized = json_decode( stripslashes( $_POST[\'customized\'] ), true );
// Make sure it\'s a proper array
if( !empty( $customized ) && is_array( $customized ) ){
// Lopp the customized items
foreach ($variables_to_find as $sub_key) {
// The key in the settings array
$key = "{$option_key}[{$sub_key}]";
// If a different value was posted
if( array_key_exists( $key, $customized) ){
// Replace it in the current object with the one submitted
$example_settings[ $sub_key ] = $customized[ $key ];
}
}
}
}
}