當(dāng)前位置:首頁>WordPress建站>WordPress開發(fā)>創(chuàng)建WordPress插件設(shè)置頁面的5種方法

創(chuàng)建WordPress插件設(shè)置頁面的5種方法

從我從頭創(chuàng)建一個新的WordPress插件已有一段時間了,但是最近我決定將一些僅對我有用的代碼轉(zhuǎn)換為可以分發(fā)的完整插件。該過程的一部分涉及用插件的未來用戶可以設(shè)置的選項替換硬編碼數(shù)據(jù)。

我需要在插件中創(chuàng)建一個設(shè)置頁面,我發(fā)現(xiàn)自己想知道在瞬息萬變的WordPress世界中,最新、最好的方法是什么。讓我們看一下將設(shè)置選項頁面添加到WordPress插件的各種方法。

  1. WordPress設(shè)定API
  2. 自定義字段框架
  3. 使用代碼生成器
  4. 使用REST API
  5. VueJS
  6. React

WordPress設(shè)置API

WordPress 設(shè)置API是在WordPress 2.7引入的,允許開發(fā)人員在儀表板設(shè)置頁面添加新的字段,或創(chuàng)建新的設(shè)置字段。WordPress會智能地顯示并采取保存數(shù)據(jù):

它使您可以定義設(shè)置頁面,修改這些頁面中的部分以及這些部分中的字段。

這是本文中討論的方法中最手動的方法,但是值得了解它的工作方式,在某些情況下,這是一種可能非常簡單的方法。

首先,我們需要注冊一個新的菜單項和頁面,其中將包含我們的設(shè)置表單。讓我們在WordPress儀表板的“設(shè)置”頂級菜單項下添加頁面:

<?php

function dbi_add_settings_page() {
    add_options_page( 'Example plugin page', 'Example Plugin Menu', 'manage_options', 'dbi-example-plugin', 'dbi_render_plugin_settings_page' );
}
add_action( 'admin_menu', 'dbi_add_settings_page' );

第五個參數(shù)add_options_page是用于顯示頁面內(nèi)容的函數(shù)的名稱,它將用于輸出設(shè)置表單。該函數(shù)需要有一個表單元素和一些函數(shù)調(diào)用才能與設(shè)置API進(jìn)行通信:

<?php

function dbi_render_plugin_settings_page() {
    ?>
    <h2>Example Plugin Settings</h2>
    <form action="options.php" method="post">
        <?php 
        settings_fields( 'dbi_example_plugin_options' );
        do_settings_sections( 'dbi_example_plugin' ); ?>
        <input name="submit" class="button button-primary" type="submit" value="<?php esc_attr_e( 'Save' ); ?>" />
    </form>
    <?php
}

函數(shù)settings_fields呈現(xiàn)代碼以告知表單要執(zhí)行的操作,以及隱藏輸入以使用nonce使其安全。傳遞給函數(shù)的參數(shù)是設(shè)置組的名稱,該名稱將在以后注冊。

函數(shù)do_settings_sections是表單的關(guān)鍵部分,在這里輸出所有部分和字段(文本框、選擇框、復(fù)選框等),以便用戶可以輸入數(shù)據(jù)。同樣,該函數(shù)參數(shù)是任意的,但必須是唯一的。我們將在注冊字段時使用它。

讓我們這樣做:

<?php

function dbi_register_settings() {
    register_setting( 'dbi_example_plugin_options', 'dbi_example_plugin_options', 'dbi_example_plugin_options_validate' );
    add_settings_section( 'api_settings', 'API Settings', 'dbi_plugin_section_text', 'dbi_example_plugin' );

    add_settings_field( 'dbi_plugin_setting_api_key', 'API Key', 'dbi_plugin_setting_api_key', 'dbi_example_plugin', 'api_settings' );
    add_settings_field( 'dbi_plugin_setting_results_limit', 'Results Limit', 'dbi_plugin_setting_results_limit', 'dbi_example_plugin', 'api_settings' );
    add_settings_field( 'dbi_plugin_setting_start_date', 'Start Date', 'dbi_plugin_setting_start_date', 'dbi_example_plugin', 'api_settings' );
}
add_action( 'admin_init', 'dbi_register_settings' );

這里發(fā)生了三件事。首先,我們使用 register_setting為我們的設(shè)置在wp_options表中創(chuàng)建新記錄,其中’dbi_example_plugin_options‘作為option_name

我們的個人設(shè)置將存儲為序列化的數(shù)據(jù)數(shù)組。這非常適合將我們所有的插件設(shè)置集中在一個地方,但是,除非正確處理,否則數(shù)據(jù)序列化在遷移WordPress數(shù)據(jù)庫時可能會導(dǎo)致問題。第三個參數(shù)是函數(shù)的名稱,該函數(shù)處理在保存選項時驗證輸入的數(shù)據(jù)。

例如,確保API密鑰是一個僅包含數(shù)字和字母的32字符串:

<?php

function dbi_example_plugin_options_validate( $input ) {
    $newinput['api_key'] = trim( $input['api_key'] );
    if ( ! preg_match( '/^[a-z0-9]{32}$/i', $newinput['api_key'] ) ) {
        $newinput['api_key'] = '';
    }

    return $newinput;
}

其次,我們正在注冊一個與選項綁定的組部分。最后,我們使用 add_settings_field 來為該組注冊三個字段。所有這些都是用于保存插件設(shè)置的文本字段。

接下來,我們需要創(chuàng)建函數(shù)以顯示該部分的有用文本并在表單上呈現(xiàn)字段:

<?php

function dbi_plugin_section_text() {
    echo '<p>Here you can set all the options for using the API</p>';
}

function dbi_plugin_setting_api_key() {
    $options = get_option( 'dbi_example_plugin_options' );
    echo "<input id='dbi_plugin_setting_api_key' name='dbi_example_plugin_options[api_key]' type='text' value='{esc_attr( $options['api_key'] )}' />";
}

function dbi_plugin_setting_results_limit() {
    $options = get_option( 'dbi_example_plugin_options' );
    echo "<input id='dbi_plugin_setting_results_limit' name='dbi_example_plugin_options[results_limit]' type='text' value='{esc_attr( $options['results_limit'] )}' />";
}

function dbi_plugin_setting_start_date() {
    $options = get_option( 'dbi_example_plugin_options' );
    echo "<input id='dbi_plugin_setting_start_date' name='dbi_example_plugin_options[start_date]' type='text' value='{esc_attr( $options['start_date'] )}' />";
}

就是這樣,然后我們就有了一個設(shè)置頁面:

我們要在代碼中使用這里設(shè)置值的時候,可以通過使用get_option('dbi_example_plugin_options')來獲取這些設(shè)置的數(shù)組數(shù)據(jù)。

這種方法注冊設(shè)置選項有些繁雜,有很多字段代碼重復(fù),要不斷復(fù)制和修改,并確保所有內(nèi)容正確組合在一起。好在有開發(fā)者進(jìn)一步封裝了一些類或代碼框架,以便大家可以更方便地添加設(shè)置:

自定義字段框架

談到PHP框架,我想展示一種無需使用WordPress設(shè)置API即可創(chuàng)建設(shè)置頁面的替代方法。在為客戶端構(gòu)建站點時,如果需要設(shè)置頁面,則默認(rèn)使用“Advanced Custom Fields ”插件(簡稱ACF)創(chuàng)建選項頁面,并使用它來定義字段。

這是我喜歡使用ACF的眾多原因之一:它使復(fù)雜的WordPress變得簡單。(您是否看過ACF Blocks,它是一個PHP包裝器,可在不接觸React的情況下為古騰堡編輯器注冊塊?)

但是,在構(gòu)建用于分發(fā)的插件或主題時,您不能依賴安裝了ACF的用戶。在這里我推薦“ Carbon Fields ”框架。與ACF不同,Carbon Fields不是插件,通常作為庫安裝在插件內(nèi)部,推薦的方法是使用Composer。

提示:如果確實使用Composer在插件中安裝Carbon Fields,請記住通過為 Composer軟件包的名稱空間加上前綴來避免WordPress依賴關(guān)系管理。

安裝完成后,首先確保引入 Composer 的autoload.php文件,然后使用下面的函數(shù)啟動Carbon Fields庫:

<?php

function dbi_load_carbon_fields() {
    \Carbon_Fields\Carbon_Fields::boot();
}
add_action( 'after_setup_theme', 'dbi_load_carbon_fields' );

要復(fù)制我們使用WordPress設(shè)置API所做的工作,只需要使用下面簡單的代碼:

<?php

use Carbon_Fields\Container;
use Carbon_Fields\Field;

function dbi_add_plugin_settings_page() {
    Container::make( 'theme_options', __( 'Example Plugin Page' ) )
        ->set_page_parent( 'options-general.php' )
        ->add_fields( array(
            Field::make( 'text', 'dbi_api_key', 'API Key' )
                ->set_attribute( maxLength, 32 ),
            Field::make( 'text', 'dbi_results_limit', 'Results Limit' )
                ->set_attribute( 'min', 1 )
                ->set_attribute( 'max', 100 )
                ->set_default_value( 10 ),
            Field::make( 'date', 'dbi_start_date', 'Start Date' ),
        ) );
}
add_action( 'carbon_fields_register_fields', 'dbi_add_plugin_settings_page' );

如您所見,該框架使將字段變得更加用容易和友好,例如將默認(rèn)值、最小值和最大值添加到“結(jié)果限制”字段中,以及將“開始日期”字段轉(zhuǎn)換為日期選擇器–使用設(shè)置API需要一些編碼才能實現(xiàn)。

要使用該設(shè)置保存的數(shù)據(jù),您需要使用以下carbon_get_theme_option()函數(shù):

<?php 

$api_key = carbon_get_theme_option( 'dbi_api_key' );

框架可以使用更少的代碼來實現(xiàn)功能,讓您更專注于編寫插件代碼,而不是重頭開始編寫設(shè)置部分的代碼。

使用代碼生成器

另一種比WordPress設(shè)置API、以及框架更簡便的方法是使用以下WordPress生成器之一:

讓我們使用WordPress選項頁面生成器重新創(chuàng)建設(shè)置頁面。它僅支持少數(shù)字段類型。文字、文本域、選擇、單選、復(fù)選框,沒有日期選擇器。

以下是通過生成器生成的代碼,可以直接在插件中使用,并以與WordPress設(shè)置API相同的方式使用數(shù)據(jù):

<?php

/**
 * Generated by the WordPress Option Page generator
 * at http://jeremyhixon.com/wp-tools/option-page/
 */

class MyExamplePlugin {
	private $my_example_plugin_options;

	public function __construct() {
		add_action( 'admin_menu', array( $this, 'my_example_plugin_add_plugin_page' ) );
		add_action( 'admin_init', array( $this, 'my_example_plugin_page_init' ) );
	}

	public function my_example_plugin_add_plugin_page() {
		add_options_page(
			'My Example Plugin', // page_title
			'My Example Plugin', // menu_title
			'manage_options', // capability
			'my-example-plugin', // menu_slug
			array( $this, 'my_example_plugin_create_admin_page' ) // function
		);
	}

	public function my_example_plugin_create_admin_page() {
		$this->my_example_plugin_options = get_option( 'my_example_plugin_option_name' ); ?>

		<div class="wrap">
			<h2>My Example Plugin</h2>
			<p></p>
			<?php settings_errors(); ?>

			<form method="post" action="options.php">
				<?php
					settings_fields( 'my_example_plugin_option_group' );
					do_settings_sections( 'my-example-plugin-admin' );
					submit_button();
				?>
			</form>
		</div>
	<?php }

	public function my_example_plugin_page_init() {
		register_setting(
			'my_example_plugin_option_group', // option_group
			'my_example_plugin_option_name', // option_name
			array( $this, 'my_example_plugin_sanitize' ) // sanitize_callback
		);

		add_settings_section(
			'my_example_plugin_setting_section', // id
			'Settings', // title
			array( $this, 'my_example_plugin_section_info' ), // callback
			'my-example-plugin-admin' // page
		);

		add_settings_field(
			'api_key_0', // id
			'API Key', // title
			array( $this, 'api_key_0_callback' ), // callback
			'my-example-plugin-admin', // page
			'my_example_plugin_setting_section' // section
		);

		add_settings_field(
			'results_limit_1', // id
			'Results Limit', // title
			array( $this, 'results_limit_1_callback' ), // callback
			'my-example-plugin-admin', // page
			'my_example_plugin_setting_section' // section
		);

		add_settings_field(
			'start_date_2', // id
			'Start Date', // title
			array( $this, 'start_date_2_callback' ), // callback
			'my-example-plugin-admin', // page
			'my_example_plugin_setting_section' // section
		);
	}

	public function my_example_plugin_sanitize($input) {
		$sanitary_values = array();
		if ( isset( $input['api_key_0'] ) ) {
			$sanitary_values['api_key_0'] = sanitize_text_field( $input['api_key_0'] );
		}

		if ( isset( $input['results_limit_1'] ) ) {
			$sanitary_values['results_limit_1'] = sanitize_text_field( $input['results_limit_1'] );
		}

		if ( isset( $input['start_date_2'] ) ) {
			$sanitary_values['start_date_2'] = sanitize_text_field( $input['start_date_2'] );
		}

		return $sanitary_values;
	}

	public function my_example_plugin_section_info() {
		
	}

	public function api_key_0_callback() {
		printf(
			'<input class="regular-text" type="text" name="my_example_plugin_option_name[api_key_0]" id="api_key_0" value="%s">',
			isset( $this->my_example_plugin_options['api_key_0'] ) ? esc_attr( $this->my_example_plugin_options['api_key_0']) : ''
		);
	}

	public function results_limit_1_callback() {
		printf(
			'<input class="regular-text" type="text" name="my_example_plugin_option_name[results_limit_1]" id="results_limit_1" value="%s">',
			isset( $this->my_example_plugin_options['results_limit_1'] ) ? esc_attr( $this->my_example_plugin_options['results_limit_1']) : ''
		);
	}

	public function start_date_2_callback() {
		printf(
			'<input class="regular-text" type="text" name="my_example_plugin_option_name[start_date_2]" id="start_date_2" value="%s">',
			isset( $this->my_example_plugin_options['start_date_2'] ) ? esc_attr( $this->my_example_plugin_options['start_date_2']) : ''
		);
	}

}
if ( is_admin() )
	$my_example_plugin = new MyExamplePlugin();

/* 
 * Retrieve this value with:
 * $my_example_plugin_options = get_option( 'my_example_plugin_option_name' ); // Array of All Options
 * $api_key_0 = $my_example_plugin_options['api_key_0']; // API Key
 * $results_limit_1 = $my_example_plugin_options['results_limit_1']; // Results Limit
 * $start_date_2 = $my_example_plugin_options['start_date_2']; // Start Date
 */

生成器是一個非常有用的工具,可通過一個現(xiàn)成的設(shè)置頁面啟動您的插件,無需進(jìn)行大量編碼即可對其進(jìn)行調(diào)整。它們還可以幫助您學(xué)習(xí)代碼的工作原理,分離現(xiàn)有代碼并查看它們?nèi)绾谓M合在一起。但是,從長遠(yuǎn)來看,對于需要對設(shè)置代碼進(jìn)行大量更改的插件來說,它們可能不是最佳選擇。

使用REST API

WordPress REST API的許多重要用途之一就是改善您的插件或主題設(shè)置屏幕。

在《使用WordPress REST API創(chuàng)建WordPress設(shè)置頁面》一文中,Josh Pollock深入探討了如何使用REST API和jQuery 創(chuàng)建設(shè)置頁面。我不會用這種技術(shù)來重新創(chuàng)建設(shè)置頁面,因為本文是一篇非常詳盡的教程。

REST API可以提供優(yōu)于傳統(tǒng) admin-ajax.php 請求的性能優(yōu)勢,再加上單擊“保存”無需刷新頁面即可在后臺保存表單設(shè)置,這種方法比WordPress設(shè)置API更友好。

Josh指出,隨著添加設(shè)置和表單變得越來越復(fù)雜,“使用jQuery將會做得越來越多,這很難管理而且會更簡單,并且如果您使用VueJS或React可以提供更好的用戶體驗” ,這使我很好地了解了下一個方法,即VueJS支持的設(shè)置頁面。

使用VueJS

在去年收購 WP User Manager 插件的過程中,我調(diào)查了代碼庫以了解其編寫方式,并發(fā)現(xiàn)設(shè)置頁面由使用REST API和VueJS的軟件包 –  wp-optionskit 提供支持 :

該軟件包可隨Composer一起安裝,并使用此處的代碼實例化和配置設(shè)置頁面。這是我們的示例設(shè)置頁面的外觀:

我喜歡這種方法的地方在于,它允許您僅通過在PHP中配置數(shù)據(jù)數(shù)組來生成具有多個選項卡和小節(jié)的復(fù)雜設(shè)置頁面。與其他方法一樣,設(shè)置數(shù)據(jù)存儲在選項表的一條記錄中,因此這是一種檢索和使用保存的數(shù)據(jù)的熟悉方法。

等一下,VueJS?WordPress不會全力投入React嗎?

談?wù)凴eact

盡管WordPress采用了 React 來構(gòu)建WordPress編輯器界面(WooCommerce甚至使用 React 重構(gòu)了后臺界面),我還沒有看到任何以 React 為基礎(chǔ)的框架,用于創(chuàng)建插件的設(shè)置頁面。但是,正如我們在wp-optionskit中看到的那樣,使用REST API為在WordPress管理員中廣泛使用VueJS或React打開了大門。

總結(jié)

與萬物發(fā)展一樣,實現(xiàn)同一事物的方法有很多,而您為一個項目選擇的方法可能與另一個項目不同。目前,我個人最喜歡的是wp-optionskit,因為它允許多個設(shè)置選項卡和小節(jié),并且在保存時提供更好的用戶體驗。

您用于為插件創(chuàng)建WordPress設(shè)置頁面的方法是什么?歡迎在文章中評論告訴我們!

原文出自: https://deliciousbrains.com/create-wordpress-plugin-settings-page/ ,由 WordPress大學(xué) 翻譯整理。

聲明:本站所有文章,如無特殊說明或標(biāo)注,均為本站原創(chuàng)發(fā)布。任何個人或組織,在未征得本站同意時,禁止復(fù)制、盜用、采集、發(fā)布本站內(nèi)容到任何網(wǎng)站、書籍等各類媒體平臺。如若本站內(nèi)容侵犯了原著者的合法權(quán)益,可聯(lián)系我們進(jìn)行處理。

給TA打賞
共{{data.count}}人
人已打賞
歡迎關(guān)注WordPress大學(xué)公眾號 WPDAXUE
WordPress開發(fā)

使用WordPress REST API創(chuàng)建WordPress設(shè)置頁面

2020-2-23 11:29:48

WordPress開發(fā)

圖解WordPress評論表單鉤子

2020-2-24 7:50:39

0 條回復(fù) A文章作者 M管理員
    暫無討論,說說你的看法吧
?
個人中心
購物車
優(yōu)惠劵
今日簽到
有新私信 私信列表
搜索

芦溪县| 平顺县| 龙江县| 微博| 米泉市| 镇巴县| 阳江市| 三明市| 射洪县| 桑日县| 云龙县| 兴城市| 文登市| 沂南县| 应城市| 临高县| 大方县| 汶川县| 儋州市| 舟曲县| 锡林郭勒盟| 共和县| 八宿县| 恩平市| 贵港市| 五峰| 常熟市| 区。| 裕民县| 修水县| 达州市| 大庆市| 昭通市| 姜堰市| 江口县| 丰原市| 池州市| 旬邑县| 盱眙县| 荣成市| 平和县|