WordPress插件开发笔记(五): 分页显示设置页

2018-10-27  本文已影响19人  破旧的大卡车

有时, 为了方便, 我们需要分页显示设置页面. 其实一个好的插件往往会包含一个用户欢迎页面, 告诉用户该插件是干啥的, 以及在每次更新时, 显示注意事项. 此外, 可能你还想写点插件开发的故(捐)事(赠).

我们下面就以添加一个欢迎页面来说明如何分页显示设置页. 首先, 我们需要一个新的变量来判断我们处在哪一个分页上, 然后根据具体的tab来呈现不同的setting_page. 为此, 在includes/admin_settings.phpl2h_admin_setting_class中添加一个变量$active_tab:

if( !class_exists( 'l2h_admin_setting_class' ) )
{
  class l2h_admin_setting_class
  {
    /**
     * Holds the values to be used in the fields callbacks
     */
    private $options, $active_tab;
// More code here ...

然后, 我们新建一个欢迎页的settings_section:

 public function l2h_admin_init(){
      /**
       * Welcome Screen
       */
      // We must declare the welcome_page if you want Submit on welcome page
      //register_setting( 'l2h_welcome_page', 'l2h_options' );
      add_settings_section(
        'l2h_pluginPage_section_welcome',
        __( 'Welcome &amp; Support<hr >', 'val2h' ),
        array( $this, 'l2h_settings_wellcome_callback' ),
        'l2h_welcome_page'
      );
/*      add_settings_field(
        'upgrade',
        __( 'Shall we <i>upgrade</i> now?', 'val2h' ),
        array( $this, 'l2h_checkbox_render' ),
        'l2h_welcome_page',
        'l2h_pluginPage_section_welcome',
        array(
          'field' => 'upgrade'
        )
      );
 */
// More code here ...
    /**
     * The callbacks
     */

    public function l2h_settings_wellcome_callback(  ) {
      echo <<<EOF
This is the Welcome page.
EOF;
    }
// More code here...

在上述例子中, 我们还演示了如何在welcome页面提交数据, 此时你首先需要注释掉register_setting那一行, 然后通过add_settings_field 添加新的设置项到welcome页面.

至此, 其实就是新建了一个变量来判断页面, 添加了一个welcome页面. 而具体的页面呈现代码是includes/admin_page.php:

<div class='wrap'>
  <h2>LaTeX2HTML Setting Page</h2>
  <?php
   $this->active_tab =  isset( $_GET['tab'] )  ?  $_GET['tab'] : 'welcome';
  ?>
  <h2 class="nav-tab-wrapper">
    <a href="?page=latex2html&tab=welcome" class="nav-tab <?php echo $this->active_tab == 'welcome' ? 'nav-tab-active' : ''; ?>">Welcome &amp; Support</a>
    <a href="?page=latex2html&tab=settings" class="nav-tab <?php echo $this->active_tab == 'settings' ? 'nav-tab-active' : ''; ?>">Settings</a><br />
  </h2>
  <form action='options.php' method='post'>
  <?php
   if( $this->active_tab == 'welcome' ){
     // This prints out all hidden setting fields
     @settings_fields( 'l2h_welcome_page' );
     @do_settings_sections( 'l2h_welcome_page' );
   }else{
     @settings_fields( 'l2h_setting_page' );
     @do_settings_sections( 'l2h_setting_page' );
     @submit_button();
   }
    ?>
  </form>
</div>

意思非常明了, 首先用h2添加两个tab链接, 链接里用&tab=welcom或者&tab=setting来标记当前页面. 然后, 我们通过$_GET取得该标签, 最后通过if判断标签呈现不同的页面. 非常简单吧, 哈哈!

附注: 本节主要参考The WordPress Settings API, Part 5: Tabbed Navigation For Settings.

上一篇 下一篇

猜你喜欢

热点阅读