2012-07-02 48 views
1

我想在我的WordPress主題選項中設置一些默認值,這樣當主題激活時,我可以獲取字段的默認值。以下是我的代碼,它顯示主題選項頁面中的默認值,但在保存選項之前,我無法在變量中獲取默認值。 有沒有辦法在保存之前從主題選項中獲取默認值?謝謝。從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']); ?>" /> 

回答

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; 
}