有時, 為了方便, 我們需要分頁顯示設置頁面. 其實一個好的插件往往會包含一個用戶歡迎頁面, 告訴用戶該插件是干啥的, 以及在每次更新時, 顯示注意事項. 此外, 可能你還想寫點插件開發(fā)的故(捐)事(贈).
我們下面就以添加一個歡迎頁面來說明如何分頁顯示設置頁. 首先, 我們需要一個新的變量來判斷我們處在哪一個分頁上, 然后根據(jù)具體的tab來呈現(xiàn)不同的setting_page. 為此, 在includes/admin_settings.php
的l2h_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 & 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頁面提交數(shù)據(jù), 此時你首先需要注釋掉register_setting
那一行, 然后通過add_settings_field
添加新的設置項到welcome頁面.
至此, 其實就是新建了一個變量來判斷頁面, 添加了一個welcome頁面. 而具體的頁面呈現(xiàn)代碼是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 & 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
判斷標簽呈現(xiàn)不同的頁面. 非常簡單吧, 哈哈!
附注: 本節(jié)主要參考The WordPress Settings API, Part 5: Tabbed Navigation For Settings.