1

我想在我的 wordpress 主题选项中设置一些默认值,以便在激活主题时,我可以获得字段的默认值。以下是我的代码,它在主题选项页面中显示默认值,但在保存选项之前我无法获取变量中的默认值。无论如何在保存之前从主题选项中获取默认值?谢谢。

//set default options
$sa_options = array(
    'footer_copyright' => '© ' . date('Y') . ' ' . get_bloginfo('name'),
    'intro_text' => 'some text',
    'featured_cat' => ''    
);


//register settings
function sa_register_settings() {
    register_setting( 'sa_theme_options', 'sa_options', 'sa_validate_options' );
}
add_action( 'admin_init', 'sa_register_settings' );


//add theme options page
function sa_theme_options() {
    add_theme_page( 'Theme Options', 'Theme Options', 'edit_theme_options', 'theme_options', 'sa_theme_options_page' );
}
add_action( 'admin_menu', 'sa_theme_options' );


// Function to generate options page
function sa_theme_options_page() {

    global $sa_options;

    <?php if ( false !== $_REQUEST['updated'] ) : ?>
    <div class="updated fade"><p><?php _e( 'Options saved' ); ?></p></div>
    <?php endif; ?>

    <form method="post" action="options.php">

    <?php $settings = get_option( 'sa_options', $sa_options ); ?>

    <?php settings_fields( 'sa_theme_options' ); ?>

    <input id="footer_copyright" name="sa_options[footer_copyright]" type="text" value="<?php  esc_attr_e($settings['footer_copyright']); ?>" />
4

1 回答 1

2

这是我的做法:定义一个获取默认值函数

function sa_theme_get_defaults(){
    return = array(
        'footer_copyright' => '&copy; ' . date('Y') . ' ' . get_bloginfo('name'),
        'intro_text' => 'some text',
        'featured_cat' => ''
    );
}

然后在你的sa_theme_options_page()替换:

<?php $settings = get_option( 'sa_options', $sa_options ); ?>

和 :

<?php $settings = get_option( 'sa_options', sa_theme_get_defaults() ); ?>

并在您的sa_validate_options()函数中获取默认值并遍历数组,例如:

function sa_validate_options($input){
    //do regular validation stuff
    //...
    //...

    //get all options
    $options = get_option( 'sa_options', sa_theme_get_defaults() );
    //update only the needed options
    foreach ($input as $key => $value){
        $options[$key] = $value;
    }
    //return all options
    return $options;
}
于 2012-07-03T08:41:42.660 回答