我正在使用一个类将主题选项页添加到我的主题中。
我需要在主题激活或安装时设置一些默认值,因为其中一些值是字符串,如果我尝试使用get_option
, 我不知道用户是否真的将其留空,或者根本没有设置。
<?php
class Theme_Options {
public function __construct() {
// We only need to register the admin panel on the back-end
if ( is_admin() ) {
add_action( \'admin_menu\', array( \'Theme_Options\', \'add_admin_menu\' ) );
add_action( \'admin_init\', array( \'Theme_Options\', \'register_settings\' ) );
}
}
// Returns all theme options
public static function get_theme_options() {
return get_option( \'theme_options\' );
}
// Returns single theme option
public static function get_theme_option_value( $id ) {
$options = self::get_theme_options();
if ( isset( $options[$id] ) ) {
return $options[$id];
}
}
// Add sub menu page
public static function add_admin_menu() {
add_menu_page(
esc_html__( \'Theme\\\'s Options\', \'sample\' ),
esc_html__( \'Theme\\\'s Options\', \'sample\' ),
\'manage_options\',
\'theme-settings\',
array( \'Theme_Options\', \'create_admin_page\' )
);
}
// Register a setting and its sanitization callback.
public static function register_settings() {
register_setting( \'theme_options\', \'theme_options\', array( \'Theme_Options\', \'sanitize\' ) );
}
// Sanitization callback
public static function sanitize( $options ) {
// If we have options lets sanitize them
if ( $options ) {
// Input
if ( ! empty( $options[\'sample_input\'] ) ) {
$options[\'sample_input\'] = sanitize_text_field( $options[\'sample_input\'] );
} else {
unset( $options[\'sample_input\'] ); // Remove from options if empty
}
}
// Return sanitized options
return $options;
}
// Settings page output
public static function create_admin_page() { ?>
<div class="wrap">
<form method="post" action="options.php">
<?php settings_fields( \'theme_options\' ); ?>
<table class="form-table"><tbody>
<tr>
<th scope="row">
<?php esc_html_e( \'Sample input\', \'sample\' ); ?>
</th>
<td>
<?php $value = self::get_theme_option_value( \'sample_input\' ); ?>
<input type="text" name="theme_options[sample_input]" value="<?php echo esc_attr( $value ); ?>">
</td>
</tr>
</tbody></table>
<?php submit_button(); ?>
</form>
</div>
<?php }
}
new Theme_Options();
// Helper function to use in theme to return a theme option value
function get_theme_option( $id = \'\' ) {
return Theme_Options::get_theme_option_value( $id );
}?>
Note: 我删除了许多不必要的行,以避免问题太长
由于该类存储的是序列化数据,因此我认为只将默认字符串保存到数据库不是最好的主意。
有没有办法在激活时运行这个类并存储一些默认值?
最合适的回答,由SO网友:TheDeadMedic 整理而成
您可以直接将逻辑写入get_theme_options
- 如果值为false
, 尚未保存任何选项:
public static function get_theme_options() {
$options = get_option( \'theme_options\' );
if ( $options === false ) {
$options = [
\'key\' => \'default_value\',
];
add_option( \'theme_options\', $options );
}
return $options;
}