在 WordPress 中添加自定义后台设置项步骤如下:
functions.php
文件或者编辑主题的 functions.php
文件。admin_menu
钩子,用于在 WordPress 后台添加页面和菜单项,示例代码如下:function add_theme_menu() {
add_menu_page( '主题选项', '主题选项', 'manage_options', 'theme-options', 'theme_settings_page' );
}
add_action( 'admin_menu', 'add_theme_menu' );
theme_settings_page
,用于渲染设置页面,示例代码如下:function theme_settings_page() {
?>
<div class="wrap">
<h1>主题选项</h1>
<form method="post" action="options.php">
<?php
settings_fields( 'theme_settings_group' );
do_settings_sections( 'theme_settings' );
submit_button();
?>
</form>
</div>
<?php
}
theme_settings_page
函数中添加设置项,使用 add_settings_section
和 add_settings_field
函数,示例代码如下:function register_theme_settings() {
// 注册设置节
add_settings_section( 'general_section', '常规设置', 'general_section_callback', 'theme_settings' );
// 注册设置字段
add_settings_field( 'phone_number', '电话号码', 'phone_number_callback', 'theme_settings', 'general_section' );
add_settings_field( 'address', '地址', 'address_callback', 'theme_settings', 'general_section' );
// 注册设置
register_setting( 'theme_settings_group', 'phone_number' );
register_setting( 'theme_settings_group', 'address' );
}
function general_section_callback() {
echo '在此处添加常规设置';
}
function phone_number_callback() {
$phone_number = get_option( 'phone_number' );
echo '<input type="text" name="phone_number" value="' . $phone_number . '" />';
}
function address_callback() {
$address = get_option( 'address' );
echo '<textarea name="address">' . $address . '</textarea>';
}
add_action( 'admin_init', 'register_theme_settings' );
以上就是在 WordPress 主题中添加自定义后台设置项的步骤和示例代码。