首页 问答 正文

如何为WordPress主题添加自定义选项。

注册会员 / 悠然自学 / 2023-06-11/ 浏览 139 次

为WordPress主题添加自定义选项可以通过添加自定义设置页面来完成。以下是步骤:

  1. 在主题文件夹中创建一个新目录,例如“theme-options”。
  2. 在该目录中创建一个新的PHP文件,例如“options.php”。
  3. 在“options.php”文件中编写自定义HTML表单代码,该表单将包含您想要添加的选项。
  4. 在“options.php”文件中编写PHP代码,该代码将处理表单提交并将选项保存到数据库中。
  5. 在主题的functions.php文件中包含options.php文件并注册设置页面。

以下是一个简单的示例代码:

在主题的functions.php中添加以下代码:

// 添加自定义设置页面
add_action('admin_menu', 'theme_options_page');
function theme_options_page() {
  add_menu_page('主题选项', '主题选项', 'manage_options', 'theme_options', 'theme_options_callback');
}

// 输出设置页面
function theme_options_callback() {
  ?>
  <div class="wrap">
    <h1>主题选项</h1>
    <form method="post" action="options.php">
      <?php
      settings_fields('theme_options');
      do_settings_sections('theme_options');
      submit_button('保存设置', 'primary', 'submit', true);
      ?>
    </form>
  </div>
  <?php
}

// 注册设置
add_action('admin_init', 'theme_options_init');
function theme_options_init() {
  register_setting('theme_options', 'theme_options', 'theme_options_validate');
  add_settings_section('general', '一般选项', 'theme_options_general_callback', 'theme_options');
  add_settings_field('logo', '站点 Logo', 'theme_options_logo_callback', 'theme_options', 'general');
}

// 设置页面回调函数
function theme_options_general_callback() {
  echo '<p>这里可以添加关于一般选项的描述。</p>';
}

// Logo字段回调函数
function theme_options_logo_callback() {
  $options = get_option('theme_options');
  echo '<input type="text" id="logo" name="theme_options[logo]" value="' . esc_url($options['logo']) . '" size="50" />';
}

// 对保存的选项进行验证
function theme_options_validate($input) {
  $output = array();
  $output['logo'] = esc_url_raw($input['logo']);
  return $output;
} 

以上代码创建了一个名为“主题选项”的设置页面,并在其中包含一个名为“站点 Logo”的自定义选项。

在主题文件夹中的“theme-options”目录中创建一个名为“options.php”的文件,并添加以下代码:

<div class="wrap">
  <h1>主题选项</h1>
  <form method="post" action="options.php">
    <?php
    settings_fields('theme_options');
    do_settings_sections('theme_options');
    submit_button('保存设置', 'primary', 'submit', true);
    ?>
  </form>
</div> 

在此基础上,您可以按照上述步骤添加自定义选项。

大家谈论
    我的见解