搜尋
首頁後端開發php教程探索 WordPress 設定 API 中的主題選項,第 4 部分

在上一篇文章中,我們深入研究了 WordPress API 支援的各種類型的選單。儘管它們不一定是設定 API 的一部分,但它們在開發中發揮關鍵作用,尤其是在開發更高級的插件和主題時。

本文將在我們開始透過重構現有設定並新增幾個新頁面來建立沙盒主題時將選單投入實際使用。請注意,如果您剛加入我們,請確保您已閱讀先前的文章,並且您已從 GitHub 上的儲存庫中取得了最新版本的沙盒主題。

開始之前:本文包含大量程式碼。在本文的前半部分,我們將重構現有程式碼。在下半年,我們將從頭開始編寫一些功能。重要的是,您需要花時間閱讀每個部分及其程式碼,並確保在繼續下一部分之前完全理解正在發生的事情。盡量避免複製和貼上下面的程式碼。

作者註:本文將引導您完成引入主題選項設定的新部分的過程,但本文並未完成該過程 - 請在此評論線程中閱讀更多內容。我知道我知道這一點,我很抱歉沒有在文章中澄清這一點,我將在本月晚些時候的下一篇文章中提供完整的工作版本!


一些內務管理

如果您已經完成了前面的範例,那麼您應該在 functions.php 中配置了許多不同的選單。由於我們將對我們的主題採取更實用的方法,因此我們需要清理先前範例中編寫的一些內容。我知道編寫大量程式碼只是為了刪除它似乎有點麻煩,但是前面的範例旨在為理解 WordPress 提供的功能奠定基礎,以便我們將功能付諸實踐。

我們要做的第一件事是找到將沙盒選項新增到外掛程式選單的兩個函數呼叫:

function sandbox_example_plugin_menu() {

	add_plugins_page(
		'Sandbox Plugin', 			// The title to be displayed in the browser window for this page.
		'Sandbox Plugin',			// The text to be displayed for this menu item
		'administrator',			// Which type of users can see this menu item
		'sandbox_plugin_options',	// The unique ID - that is, the slug - for this menu item
		'sandbox_plugin_display'	// The name of the function to call when rendering this menu's page
	);

} // end sandbox_example_theme_menu
add_action('admin_menu', 'sandbox_example_plugin_menu');

function sandbox_plugin_display() {

	// Create a header in the default WordPress 'wrap' container
	$html = '<div class="wrap">';
		$html .= '<h2 id="Sandbox-Plugin-Options">Sandbox Plugin Options</h2>';
		$html .= '<p class="description">There are currently no options. This is just for demo purposes.</p>';
	$html .= '</div>';
	
	// Send the markup to the browser
	echo $html;
	
} // end sandbox_plugin_display

functions.php中刪除它。

接下來,我們要刪除新增頂級選單的選項。我們將在本文後面重新訪問此程式碼,但它與我們最初創建的程式碼略有不同。

function sandbox_create_menu_page() {

	add_menu_page(
		'Sandbox Options',			// The title to be displayed on this menu's corresponding page
		'Sandbox',					// The text to be displayed for this actual menu item
		'administrator',			// Which type of users can see this menu
		'sandbox',					// The unique ID - that is, the slug - for this menu item
		'sandbox_menu_page_display',// The name of the function to call when rendering this menu's page
		''
	);
	
	add_submenu_page(
		'sandbox',					// Register this submenu with the menu defined above
		'Sandbox Options',			// The text to the display in the browser when this menu item is active
		'Options',					// The text for this menu item
		'administrator',			// Which type of users can see this menu
		'sandbox_options',			// The unique ID - the slug - for this menu item
		'sandbox_options_display' 	// The function used to render this menu's page to the screen
	);

} // end sandbox_create_menu_page
add_action('admin_menu', 'sandbox_create_menu_page');

function sandbox_menu_page_display() {
	
	// Create a header in the default WordPress 'wrap' container
	$html = '<div class="wrap">';
		$html .= '<h2 id="Sandbox">Sandbox</h2>';
	$html .= '</div>';
	
	// Send the markup to the browser
	echo $html;
	
} // end sandbox_menu_page_display

function sandbox_options_display() {

	// Create a header in the default WordPress 'wrap' container
	$html = '<div class="wrap">';
		$html .= '<h2 id="Sandbox-Options">Sandbox Options</h2>';
	$html .= '</div>';
	
	// Send the markup to the browser
	echo $html;
	
} // end sandbox_options_display

此時,您應該在我們建立的 WordPress 管理區域中留下兩個特定功能:

  • 外觀選單下的「沙盒主題」選單項目。
  • 「設定」選單下「一般」設定下的一組三個選項。

如果您看到這兩個選項,就可以開始了;否則,請驗證您的 functions.php 是否類似於以下程式碼:

function sandbox_example_theme_menu() {

	add_theme_page(
		'Sandbox Theme', 			// The title to be displayed in the browser window for this page.
		'Sandbox Theme',			// The text to be displayed for this menu item
		'administrator',			// Which type of users can see this menu item
		'sandbox_theme_options',	// The unique ID - that is, the slug - for this menu item
		'sandbox_theme_display'		// The name of the function to call when rendering this menu's page
	);

} // end sandbox_example_theme_menu
add_action('admin_menu', 'sandbox_example_theme_menu');

function sandbox_theme_display() {

	// Create a header in the default WordPress 'wrap' container
	$html = '<div class="wrap">';
		$html .= '<h2 id="Sandbox-Theme-Options">Sandbox Theme Options</h2>';
		$html .= '<p class="description">There are currently no options. This is just for demo purposes.</p>';
	$html .= '</div>';
	
	// Send the markup to the browser
	echo $html;
	
} // end sandbox_theme_display

/* ------------------------------------------------------------------------ *
 * Setting Registration
 * ------------------------------------------------------------------------ */ 
 
function sandbox_initialize_theme_options() {

	// First, we register a section. This is necessary since all future options must belong to a 
	add_settings_section(
		'general_settings_section',			// ID used to identify this section and with which to register options
		'Sandbox Options',					// Title to be displayed on the administration page
		'sandbox_general_options_callback',	// Callback used to render the description of the section
		'general'							// Page on which to add this section of options
	);
	
	// Next, we'll introduce the fields for toggling the visibility of content elements.
	add_settings_field(	
		'show_header',						// ID used to identify the field throughout the theme
		'Header',							// The label to the left of the option interface element
		'sandbox_toggle_header_callback',	// The name of the function responsible for rendering the option interface
		'general',							// The page on which this option will be displayed
		'general_settings_section',			// The name of the section to which this field belongs
		array(								// The array of arguments to pass to the callback. In this case, just a description.
			'Activate this setting to display the header.'
		)
	);
	
	add_settings_field(	
		'show_content',						
		'Content',				
		'sandbox_toggle_content_callback',	
		'general',							
		'general_settings_section',			
		array(								
			'Activate this setting to display the content.'
		)
	);
	
	add_settings_field(	
		'show_footer',						
		'Footer',				
		'sandbox_toggle_footer_callback',	
		'general',							
		'general_settings_section',			
		array(								
			'Activate this setting to display the footer.'
		)
	);
	
	// Finally, we register the fields with WordPress
	
	register_setting(
		'general',
		'show_header'
	);
	
	register_setting(
		'general',
		'show_content'
	);
	
	register_setting(
		'general',
		'show_footer'
	);
	
} // end sandbox_initialize_theme_options
add_action('admin_init', 'sandbox_initialize_theme_options');

/* ------------------------------------------------------------------------ *
 * Section Callbacks
 * ------------------------------------------------------------------------ */ 

function sandbox_general_options_callback() {
	echo '<p>Select which areas of content you wish to display.</p>';
} // end sandbox_general_options_callback

/* ------------------------------------------------------------------------ *
 * Field Callbacks
 * ------------------------------------------------------------------------ */ 

function sandbox_toggle_header_callback($args) {
	
	// Note the ID and the name attribute of the element match that of the ID in the call to add_settings_field
	$html = '<input type="checkbox" id="show_header" name="show_header" value="1" ' . checked(1, get_option('show_header'), false) . '/>'; 
	
	// Here, we'll take the first argument of the array and add it to a label next to the checkbox
	$html .= '<label for="show_header"> '  . $args[0] . '</label>'; 
	
	echo $html;
	
} // end sandbox_toggle_header_callback

function sandbox_toggle_content_callback($args) {

	$html = '<input type="checkbox" id="show_content" name="show_content" value="1" ' . checked(1, get_option('show_content'), false) . '/>'; 
	$html .= '<label for="show_content"> '  . $args[0] . '</label>'; 
	
	echo $html;
	
} // end sandbox_toggle_content_callback

function sandbox_toggle_footer_callback($args) {
	
	$html = '<input type="checkbox" id="show_footer" name="show_footer" value="1" ' . checked(1, get_option('show_footer'), false) . '/>'; 
	$html .= '<label for="show_footer"> '  . $args[0] . '</label>'; 
	
	echo $html;
	
} // end sandbox_toggle_footer_callback

此時,我們已準備好開始。


規劃我們的選擇

在編寫任何程式碼之前,規劃我們要做什麼很重要。此時,我們已經編寫了一些有用的功能 - 我們使用戶能夠切換頁眉、內容和頁腳區域的可見性。問題是,這些選項目前位於「設定」選單的「常規」頁面上。由於我們正在開發一個主題,因此我們應該將其包含在主題的選項頁面中。

最重要的是,這三個選項對於一個有用的主題來說是不夠的。用戶在部落格上展示其社交網路已變得越來越普遍,因此我們計劃讓用戶能夠添加指向其 Twitter、Facebook 和 Google 帳戶的連結。

考慮到這一點,我們可以規劃以下兩個部分:

  • 顯示選項
    • 標題
    • 內容
    • Footer
  • 社交選項
    • 推特
    • 臉書
    • Google

為了更進一步,我們將在沙盒主題的選項頁面中引入這些選項,該頁面可以在外觀選單下存取。此外,每個部分都可以透過頁面導航中自己的選項卡進行存取。


建立選項

重構選項頁面

我們的選項頁面將在本文中變得更加高級,因此最好為此做好準備。查看我們的選項頁面,回呼函數如下所示:

function sandbox_theme_display() {

	// Create a header in the default WordPress 'wrap' container
	$html = '<div class="wrap">';
		$html .= '<h2 id="Sandbox-Theme-Options">Sandbox Theme Options</h2>';
		$html .= '<p class="description">There are currently no options. This is just for demo purposes.</p>';
	$html .= '</div>';

	// Send the markup to the browser
	echo $html;

} // end sandbox_theme_display

由於它會變得更高級,所以我們需要對其進行一些重構。具體來說,我們將執行以下操作:

  • 為選項頁面提供一個圖標,以便外觀與 WordPress 外觀更加一致
  • 刪除頁面描述
  • 將 HTML 的 PHP 字串重構為 HTML 區塊,以便更容易維護逾時
  • 引入顯示設定錯誤的功能
  • 建立一個表單來容納我們的選項

這相對簡單。在這種情況下,程式碼可以更好地解釋我們正在做的事情,嘗試逐行分解它。查看下面的程式碼,密切注意註釋,然後確保您的回調看起來像這樣:

function sandbox_theme_display() {
?>
	<!-- Create a header in the default WordPress 'wrap' container -->
	<div class="wrap">

		<!-- Add the icon to the page -->
		<div id="icon-themes" class="icon32"></div>
		<h2 id="Sandbox-Theme-Options">Sandbox Theme Options</h2>

		<!-- Make a call to the WordPress function for rendering errors when settings are saved. -->
		<?php settings_errors(); ?>

		<!-- Create the form that will be used to render our options -->
		<form method="post" action="options.php">
			<?php settings_fields( 'general' ); ?>
			<?php do_settings_sections( 'general' ); ?>			
			<?php submit_button(); ?>
		</form>

	</div><!-- /.wrap -->
<?php
} // end sandbox_theme_display

如果您的所有程式碼都正確,您的選項頁面應如下所示:

探索 WordPress 设置 API 中的主题选项,第 4 部分

#

重新调整我们的选择

现在主题的选项页面已经成型,是时候将我们到目前为止创建的选项(即显示选项)移动到主题的选项页面上。回想一下上一篇文章,我们将每个新选项添加​​到“常规”设置页面的“沙盒选项”标签下。现在我们要将其移至其自己的页面,我们将需要进行一些修改。我们将逐一详细介绍我们正在做的事情。

第 1 步验证选项是否存在

由于我们要创建自己的自定义选项组,而不是将字段添加到现有集合中,因此我们需要确保我们的选项集合存在于数据库中。为此,我们将调用 get_option 函数。如果它返回 false,那么我们将使用 add_option 函数添加新的选项集。

为此,请将以下代码块添加为 sandbox_initialize_theme_options 函数中的第一行:

if( false == get_option( 'sandbox_theme_display_options' ) ) {	
	add_option( 'sandbox_theme_display_options' );
} // end if

第 2 步重构我们的部分

找到对 add_settings_section 的调用并记下“title”参数。现在,它应该看起来像这样:

add_settings_section(
	'general_settings_section',			// ID used to identify this section and with which to register options
	'Sandbox Options',					// Title to be displayed on the administration page
	'sandbox_general_options_callback',	// Callback used to render the description of the section
	'general'							// Page on which to add this section of options
);

由于这些选项现在位于“沙盒选项”页面下,因此我们不希望该部分被如此标记。相反,我们将其更改为“显示选项”。

add_settings_section(
	'general_settings_section',			// ID used to identify this section and with which to register options
	'Display Options',					// Title to be displayed on the administration page
	'sandbox_general_options_callback',	// Callback used to render the description of the section
	'sandbox_theme_display_options'		// Page on which to add this section of options
);

其次,我们不再在“常规设置”页面上呈现此内容,因此我们需要将最后一个参数更改为我们主题特有的内容。我选择使用 sandbox_theme_display_options:

add_settings_section(
	'general_settings_section',			// ID used to identify this section and with which to register options
	'Display Options',					// Title to be displayed on the administration page
	'sandbox_general_options_callback',	// Callback used to render the description of the section
	'sandbox_theme_display_options'		// Page on which to add this section of options
);

第 3 步更新我们的设置字段

现在我们已经为显示选项提供了唯一的页面标识符,我们需要确保我们的设置正确引用页面,以便正确呈现它们。目前,我们对 add_settings_field 的所有调用均指“常规设置”页面:

add_settings_field(	
	'show_header',						// ID used to identify the field throughout the theme
	'Header',							// The label to the left of the option interface element
	'sandbox_toggle_header_callback',	// The name of the function responsible for rendering the option interface
	'general',							// The page on which this option will be displayed
	'general_settings_section',			// The name of the section to which this field belongs
	array(								// The array of arguments to pass to the callback. In this case, just a description.
		'Activate this setting to display the header.'
	)
);

我们需要更改第四个参数 - 即页面参数 - 以便它引用我们的新显示选项页面而不是常规页面。只需将字符串更改为 sandbox_theme_display_options 即可。这三个选项现在应如下所示:

add_settings_field(	
	'show_header',						// ID used to identify the field throughout the theme
	'Header',							// The label to the left of the option interface element
	'sandbox_toggle_header_callback',	// The name of the function responsible for rendering the option interface
	'sandbox_theme_display_options',	// The page on which this option will be displayed
	'general_settings_section',			// The name of the section to which this field belongs
	array(								// The array of arguments to pass to the callback. In this case, just a description.
		'Activate this setting to display the header.'
	)
);

add_settings_field(	
	'show_content',						
	'Content',				
	'sandbox_toggle_content_callback',	
	'sandbox_theme_display_options',					
	'general_settings_section',			
	array(								
		'Activate this setting to display the content.'
	)
);

add_settings_field(	
	'show_footer',						
	'Footer',				
	'sandbox_toggle_footer_callback',	
	'sandbox_theme_display_options',		
	'general_settings_section',			
	array(								
		'Activate this setting to display the footer.'
	)
);

第 4 步注册新设置

到目前为止,我们已使用常规页面上的设置单独注册了每个选项:

register_setting(
	'general',
	'show_header'
);

register_setting(
	'general',
	'show_content'
);

register_setting(
	'general',
	'show_footer'
);

由于我们创建了自己的选项页面以及我们自己的部分,因此我们可以将这三个注册调用合并为一个调用,该调用将为我们的新选项部分注册字段:

register_setting(
	'sandbox_theme_display_options',
	'sandbox_theme_display_options'
);

这可能是最难掌握的想法。回想一下本系列的第二篇文章,设置是它们所属的字段和部分的组合。由于我们所有的字段都属于同一部分(显示选项),因此我们使用 WordPress 注册该部分。

第 5 步更新选项元素

不要错过这一点:到目前为止,我们的选项已作为单独的设置保存在数据库中。这意味着我们可以简单地通过 ID 查找它们(例如 get_option('show_header');,但由于我们现在已将它们添加到自定义部分,因此它们是选项集合的一部分。这意味着为了读取我们的选项,我们必须首先访问选项集合,然后请求该集合的单个选项。

现在我们需要更新每个输入元素。为此,请在 functions.php 文件中找到回调函数。第一个选项应如下所示:

function sandbox_toggle_header_callback($args) {
	
	$html = '<input type="checkbox" id="show_header" name="show_header" value="1" ' . checked(1, get_option('show_header'), false) . '/>'; 
	$html .= '<label for="show_header"> '  . $args[0] . '</label>'; 
	
	echo $html;
	
} // end sandbox_toggle_header_callback

如上所述,我们的每个选项现在都是集合的一部分,因此我们需要更新引用它们的方式。我们需要...

  1. 阅读 WordPress 的选项集合
  2. 访问集合中的单个选项
  3. 更新输入元素的属性以正确引用选项集合

虽然听起来很多,但步骤很简单。查看下面的代码,密切注意注释:

function sandbox_toggle_header_callback($args) {
	
	// First, we read the options collection
	$options = get_option('sandbox_theme_display_options');
	
	// Next, we update the name attribute to access this element's ID in the context of the display options array
	// We also access the show_header element of the options collection in the call to the checked() helper function
	$html = '<input type="checkbox" id="show_header" name="sandbox_theme_display_options[show_header]" value="1" ' . checked(1, $options['show_header'], false) . '/>'; 
	
	// Here, we'll take the first argument of the array and add it to a label next to the checkbox
	$html .= '<label for="show_header"> '  . $args[0] . '</label>'; 
	
	echo $html;
	
} // end sandbox_toggle_header_callback

很简单,对吧?由于我们有三个元素,因此我们需要对每个元素进行相应的更改。除了选项名称之外,每个函数看起来几乎相同。它将读取 show_contentshow_footer,而不是 show_header

完成后,三个表单元素的最终版本应如下所示:

function sandbox_toggle_header_callback($args) {

	$options = get_option('sandbox_theme_display_options');

	$html = '<input type="checkbox" id="show_header" name="sandbox_theme_display_options[show_header]" value="1" ' . checked(1, $options['show_header'], false) . '/>'; 
	$html .= '<label for="show_header"> '  . $args[0] . '</label>'; 

	echo $html;

} // end sandbox_toggle_header_callback

function sandbox_toggle_content_callback($args) {

	$options = get_option('sandbox_theme_display_options');

	$html = '<input type="checkbox" id="show_content" name="sandbox_theme_display_options[show_content]" value="1" ' . checked(1, $options['show_content'], false) . '/>'; 
	$html .= '<label for="show_content"> '  . $args[0] . '</label>'; 

	echo $html;

} // end sandbox_toggle_content_callback

function sandbox_toggle_footer_callback($args) {

	$options = get_option('sandbox_theme_display_options');

	$html = '<input type="checkbox" id="show_footer" name="sandbox_theme_display_options[show_footer]" value="1" ' . checked(1, $options['show_footer'], false) . '/>'; 
	$html .= '<label for="show_footer"> '  . $args[0] . '</label>'; 

	echo $html;

} // end sandbox_toggle_footer_callback

第 6 步渲染选项

最后,我们准备在新的主题选项页面上呈现选项。只需调用 Settings API 中的两个函数就可以了:

  1. settings_fields 负责为选项表单呈现多种安全措施。
  2. do_settings_sections 实际上将选项呈现到页面。

每个函数都采用我们将渲染的页面的 ID。在我们的例子中,这是 sandbox_theme_display_options。为了呈现我们的选项,我们将 form 更新为如下所示:

	<form method="post" action="options.php">
		<?php settings_fields( 'sandbox_theme_display_options' ); ?>
		<?php do_settings_sections( 'sandbox_theme_display_options' ); ?>			
		<?php submit_button(); ?>
	</form>

此时,您应该能够刷新沙盒主题选项页面并看到我们的三个选项呈现如下:

探索 WordPress 设置 API 中的主题选项,第 4 部分

functions.php 的最终版本现在应如下所示:


	
	

Sandbox Theme Options

Select which areas of content you wish to display.

'; } // end sandbox_general_options_callback function sandbox_toggle_header_callback($args) { // First, we read the options collection $options = get_option('sandbox_theme_display_options'); // Next, we update the name attribute to access this element's ID in the context of the display options array // We also access the show_header element of the options collection in the call to the checked() helper function $html = '<input type="checkbox" id="show_header" name="sandbox_theme_display_options[show_header]" value="1" ' . checked(1, $options['show_header'], false) . '/>'; // Here, we'll take the first argument of the array and add it to a label next to the checkbox $html .= '<label for="show_header"> ' . $args[0] . '</label>'; echo $html; } // end sandbox_toggle_header_callback function sandbox_toggle_content_callback($args) { $options = get_option('sandbox_theme_display_options'); $html = ''; $html .= ''; echo $html; } // end sandbox_toggle_content_callback function sandbox_toggle_footer_callback($args) { $options = get_option('sandbox_theme_display_options'); $html = ''; $html .= ''; echo $html; } // end sandbox_toggle_footer_callback ?>

引入社交选项

我知道这部分有点详尽。我们采用了之前编写的大量代码并对其进行了重构以适应全新的页面。设置 API 可能具有挑战性!仅仅将现有代码重构到新页面中是不够的。因此,为了确保我们采取了自定义选项页面的流程并从头到尾引入新选项,我们现在将引入一组全新的选项。

为了与我们通常的流程保持一致,让我们准确地计划一下我们要做什么:

  • 我们需要创建一个新的字段部分
  • 将添加三个字段:一个用于 Facebook,一个用于 Twitter,一个用于 Google+
  • 我们需要更新选项页面以呈现这些新选项

创建我们的部分、字段和设置

社交选项部分

首先,让我们继续设置一个新函数并将其添加到 admin_init 挂钩中。该功能专门用于设置我们的社交选项。与我们的显示选项一样,它需要执行检查以确保选项存在,如果不存在,则应该创建它们。

这是初始函数。也请注意评论!

/**
 * Initializes the theme's social options by registering the Sections,
 * Fields, and Settings.
 *
 * This function is registered with the 'admin_init' hook.
 */ 
function sandbox_theme_intialize_social_options() {

	// If the social options don't exist, create them.
	if( false == get_option( 'sandbox_theme_social_options' ) ) {	
		add_option( 'sandbox_theme_social_options' );
	} // end if

} // end sandbox_theme_intialize_social_options
add_action( 'admin_init', 'sandbox_theme_intialize_social_options' );

接下来,我们需要添加新的设置部分。这是在上面的代码之后立即完成的:

add_settings_section(
	'social_settings_section',			// ID used to identify this section and with which to register options
	'Social Options',					// Title to be displayed on the administration page
	'sandbox_social_options_callback',	// Callback used to render the description of the section
	'sandbox_theme_social_options'		// Page on which to add this section of options
);

但我们注意到已经完成了!回想一下,第三个选项是指本节的回调函数。不要忘记定义它:

function sandbox_social_options_callback() {
	echo '<p>Provide the URL to the social networks you\'d like to display.</p>';
} // end sandbox_general_options_callback

此时,我们可以进行健全性检查,以确保该部分已正确注册到设置 API。跳回 sandbox_theme_display 函数并将以下两行添加到表单元素中。他们可以直接转到 sandbox_theme_display_options 对应项下方:

<?php settings_fields( 'sandbox_theme_social_options' ); ?>
<?php do_settings_sections( 'sandbox_theme_social_options' ); ?>

如果您已正确编写代码,您的选项页面现在应如下所示:

探索 WordPress 设置 API 中的主题选项,第 4 部分

社交选项字段

现在我们准备开始向页面添加社交选项字段。让我们首先为 Twitter 添加一个字段。在调用 add_settings_section 的下面,我们编写以下函数:

add_settings_field(	
	'twitter',						
	'Twitter',							
	'sandbox_twitter_callback',	
	'sandbox_theme_social_options',	
	'social_settings_section'
);

请注意 - 我们已将回调定义为 sandbox_twitter_callback 因此我们也需要实现该函数。正如我们对之前的选项所做的那样,我们需要获取选项集合,为该选项创建 HTML 元素,并正确设置其属性以引用该选项。请特别注意下面代码中的条件 - 为了清楚起见,对其进行了注释,但这是确保我们不会尝试读取空选项的最佳实践:

function sandbox_twitter_callback() {
	
	// First, we read the social options collection
	$options = get_option( 'sandbox_theme_social_options' );
	
	// Next, we need to make sure the element is defined in the options. If not, we'll set an empty string.
	$url = '';
	if( isset( $options['twitter'] ) ) {
		$url = $options['twitter'];
	} // end if
	
	// Render the output
	echo '<input type="text" id="twitter" name="sandbox_theme_social_options[twitter]" value="' . $options['twitter'] . '" />';
	
} // end sandbox_twitter_callback

最后,我们跳回 sandbox_theme_intialize_social_options 函数并使用 WordPress 注册新设置:

	
register_setting(
	'sandbox_theme_social_options',
	'sandbox_theme_social_options',
	'sandbox_theme_sanitize_social_options'
);

这里有一个重要的区别:到目前为止,我们只为 register_setting 函数提供两个参数 – 选项组和选项名称 – 但这一次,我们提供了第三个参数: 回调函数的名称。具体来说,该函数在数据写入数据库之前被调用。它允许您在保存参数之前处理所有参数。一般来说,这是您想要清理数据以防止保存恶意代码或格式错误的信息的时间。

所以让我们继续并删除该函数:

function sandbox_theme_sanitize_social_options( $input ) {
} // end sandbox_theme_sanitize_social_options

请注意,上面的回调接受一个我们命名为 $input 的参数。此参数是社交选项部分存在的选项的集合。由于我们允许用户在输入字段中输入原始文本,因此我们需要防止保存任何恶意代码(例如 JavaScript 或 SQL)。

为此,我们需要执行以下操作:

  • 创建一个数组,用于存储处理后的数据
  • 循环遍历每个选项并正确清理数据
  • 返回更新后的选项集合

让我们继续编写代码来执行此操作。将函数更新为如下所示:

function sandbox_theme_sanitize_social_options( $input ) {
	
	// Define the array for the updated options
	$output = array();

	// Loop through each of the options sanitizing the data
	foreach( $input as $key => $val ) {
	
		if( isset ( $input[$key] ) ) {
			$output[$key] = esc_url_raw( strip_tags( stripslashes( $input[$key] ) ) );
		} // end if	
	
	} // end foreach
	
	// Return the new collection
	return apply_filters( 'sandbox_theme_sanitize_social_options', $output, $input );

} // end sandbox_theme_sanitize_social_options

请注意,上面我们使用了三个函数,每个函数都有助于确保用户提交的数据是干净的:

  • stripslashes 是一个原生 PHP 函数,它将“取消引用带引号的”字符串
  • strip_tags 是另一个原生 PHP 函数,用于从字符串中删除 HTML 和 PHP 标签
  • esc_url_raw 是一个 WordPress 函数,它将强制使用干净的 URL

当然,上述过程很激进,但如果您想确保只允许将 URL 保存到数据库中,那么它是有效的。

请注意,最后一行实际上返回 apply_filters 函数的结果而不是数组本身。这是确保附加到同一钩子的其他函数也将被调用的最佳实践。在这个主题的背景下,显然没有其他功能;但是,这是进行专业主题开发的良好实践。

此时,保存您的工作并刷新浏览器。您的选项页面现在不仅应该显示“显示选项”,还应该显示第一个社交选项。更重要的是,您应该能够提供您的 Twitter 个人资料的 URL 并将其保存到数据库中。

探索 WordPress 设置 API 中的主题选项,第 4 部分

包括其余选项

引入 Facebook 和 Google+ 将遵循与添加 Twitter 支持所需的完全相同的步骤。主要是:

  • 定义设置字段
  • 设置回调

很简单,对吧?由于设置 API,其他一切都已处理完毕。当然,我们需要完整 - 以下是如何添加对以下网络的支持。

首先,我们将定义两个设置字段:

add_settings_field(	
	'facebook',						
	'Facebook',							
	'sandbox_facebook_callback',	
	'sandbox_theme_social_options',	
	'social_settings_section'			
);

add_settings_field(	
	'googleplus',						
	'Google+',							
	'sandbox_googleplus_callback',	
	'sandbox_theme_social_options',	
	'social_settings_section'			
);

接下来,我们将定义它们的两个回调:

function sandbox_facebook_callback() {
	
	$options = get_option( 'sandbox_theme_social_options' );
	
	$url = '';
	if( isset( $options['facebook'] ) ) {
		$url = $options['facebook'];
	} // end if
	
	// Render the output
	echo '<input type="text" id="facebook" name="sandbox_theme_social_options[facebook]" value="' . $options['facebook'] . '" />';
	
} // end sandbox_facebook_callback

function sandbox_googleplus_callback() {
	
	$options = get_option( 'sandbox_theme_social_options' );
	
	$url = '';
	if( isset( $options['googleplus'] ) ) {
		$url = $options['googleplus'];
	} // end if
	
	// Render the output
	echo '<input type="text" id="googleplus" name="sandbox_theme_social_options[googleplus]" value="' . $options['googleplus'] . '" />';
	
} // end sandbox_googleplus_callback

保存您的工作,然后再次刷新您的选项页面。现在应该有两个额外的字段 - 一个用于 Facebook,一个用于 Google+。也请随意尝试一下。

关于安全性的说明:虽然此示例可以正常运行,但在将选项保存到数据库时,我们仍然应该采取一些安全措施。在本系列的后面部分,当我们更深入地了解每个输入字段时,我们将研究最佳实践,以确保在保存数据之前对其进行清理。


渲染字段

如果我们不在实际网站上访问它们,那么这些选项有什么用呢?在结束本文之前,让我们对主题的 index 模板进行一些小更新。也就是说,我们需要确保引用我们的新选项并引入显示社交网络的功能:

<!DOCTYPE html>
<html>
	<head>	
		<title>The Complete Guide To The Settings API | Sandbox Theme</title>
	</head>
	<body>
	
		<?php $display_options = get_option( 'sandbox_theme_display_options' ); ?>
		<?php $social_options = get_option ( 'sandbox_theme_social_options' ); ?>
	
		<?php if( $display_options[ 'show_header' ] ) { ?>
			<div id="header">
				<h1 id="Sandbox-Header">Sandbox Header</h1>
			</div><!-- /#header -->
		<?php } // end if ?>
		
		<?php if( $display_options[ 'show_content' ] ) { ?>
			<div id="content">
				<?php echo $social_options['twitter'] ? '<a href="' . $social_options['twitter'] . '">Twitter</a>' : ''; ?>
				<?php echo $social_options['facebook'] ? '<a href="' . $social_options['facebook'] . '">Facebook</a>' : ''; ?>
				<?php echo $social_options['googleplus'] ? '<a href="' . $social_options['googleplus'] . '">Google+</a>' : ''; ?>
			</div><!-- /#content -->
		<?php } // end if ?>
		
		<?php if( $display_options[ 'show_footer' ] ) { ?>
			<div id="footer">
				<p>© <?php echo date('Y'); ?> All Rights Reserved.</p>
			</div><!-- /#footer -->
		<?php } // end if ?>
	
	</body>
</html>

结论

这可以说是我们在这个特定系列中曾经(或将会)最激烈的文章。如果您喜欢它,您应该非常适合开始使用设置 API 进行更高级的工作。在接下来的两篇文章中,我们将介绍导航菜单(选项卡式导航和顶级导航)到我们的菜单中。这些文章应该更短一些,代码密集度也更少。之后,我们将研究每种元素类型。

同时,尝试一下我们到目前为止所介绍的内容!

作者注:

非常感谢那些花时间评论并分享此特定帖子问题的人。希望以下内容能够澄清这一点,并继续使其成为尽可能有价值的系列!

在本教程中,我们已经添加了大量代码;但是,仍然没有有效的设置页面。在下一篇文章中,我们将对此进行完善并添加功能,以便真正为这些选项注入一些活力,因此请务必继续阅读。

也就是说,如果您碰巧遇到许多选项未保存或某些验证错误的问题。验证错误已得到修复,最新代码可在 GitHub 上找到,因此请务必查看。请注意,我会保持该项目的最新状态,以便在出现问题时,我会尽快解决它们。


相关来源

  • 获取选项
  • 添加选项
  • admin_init
  • 设置字段
  • do_settings_section

以上是探索 WordPress 設定 API 中的主題選項,第 4 部分的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
PHP:服務器端腳本語言的簡介PHP:服務器端腳本語言的簡介Apr 16, 2025 am 12:18 AM

PHP是一種服務器端腳本語言,用於動態網頁開發和服務器端應用程序。 1.PHP是一種解釋型語言,無需編譯,適合快速開發。 2.PHP代碼嵌入HTML中,易於網頁開發。 3.PHP處理服務器端邏輯,生成HTML輸出,支持用戶交互和數據處理。 4.PHP可與數據庫交互,處理表單提交,執行服務器端任務。

PHP和網絡:探索其長期影響PHP和網絡:探索其長期影響Apr 16, 2025 am 12:17 AM

PHP在過去幾十年中塑造了網絡,並將繼續在Web開發中扮演重要角色。 1)PHP起源於1994年,因其易用性和與MySQL的無縫集成成為開發者首選。 2)其核心功能包括生成動態內容和與數據庫的集成,使得網站能夠實時更新和個性化展示。 3)PHP的廣泛應用和生態系統推動了其長期影響,但也面臨版本更新和安全性挑戰。 4)近年來的性能改進,如PHP7的發布,使其能與現代語言競爭。 5)未來,PHP需應對容器化、微服務等新挑戰,但其靈活性和活躍社區使其具備適應能力。

為什麼要使用PHP?解釋的優點和好處為什麼要使用PHP?解釋的優點和好處Apr 16, 2025 am 12:16 AM

PHP的核心優勢包括易於學習、強大的web開發支持、豐富的庫和框架、高性能和可擴展性、跨平台兼容性以及成本效益高。 1)易於學習和使用,適合初學者;2)與web服務器集成好,支持多種數據庫;3)擁有如Laravel等強大框架;4)通過優化可實現高性能;5)支持多種操作系統;6)開源,降低開發成本。

揭穿神話:PHP真的是一種死語嗎?揭穿神話:PHP真的是一種死語嗎?Apr 16, 2025 am 12:15 AM

PHP沒有死。 1)PHP社區積極解決性能和安全問題,PHP7.x提升了性能。 2)PHP適合現代Web開發,廣泛用於大型網站。 3)PHP易學且服務器表現出色,但類型系統不如靜態語言嚴格。 4)PHP在內容管理和電商領域仍重要,生態系統不斷進化。 5)通過OPcache和APC等優化性能,使用OOP和設計模式提升代碼質量。

PHP與Python辯論:哪個更好?PHP與Python辯論:哪個更好?Apr 16, 2025 am 12:03 AM

PHP和Python各有優劣,選擇取決於項目需求。 1)PHP適合Web開發,易學,社區資源豐富,但語法不夠現代,性能和安全性需注意。 2)Python適用於數據科學和機器學習,語法簡潔,易學,但執行速度和內存管理有瓶頸。

PHP的目的:構建動態網站PHP的目的:構建動態網站Apr 15, 2025 am 12:18 AM

PHP用於構建動態網站,其核心功能包括:1.生成動態內容,通過與數據庫對接實時生成網頁;2.處理用戶交互和表單提交,驗證輸入並響應操作;3.管理會話和用戶認證,提供個性化體驗;4.優化性能和遵循最佳實踐,提升網站效率和安全性。

PHP:處理數據庫和服務器端邏輯PHP:處理數據庫和服務器端邏輯Apr 15, 2025 am 12:15 AM

PHP在數據庫操作和服務器端邏輯處理中使用MySQLi和PDO擴展進行數據庫交互,並通過會話管理等功能處理服務器端邏輯。 1)使用MySQLi或PDO連接數據庫,執行SQL查詢。 2)通過會話管理等功能處理HTTP請求和用戶狀態。 3)使用事務確保數據庫操作的原子性。 4)防止SQL注入,使用異常處理和關閉連接來調試。 5)通過索引和緩存優化性能,編寫可讀性高的代碼並進行錯誤處理。

您如何防止PHP中的SQL注入? (準備的陳述,PDO)您如何防止PHP中的SQL注入? (準備的陳述,PDO)Apr 15, 2025 am 12:15 AM

在PHP中使用預處理語句和PDO可以有效防範SQL注入攻擊。 1)使用PDO連接數據庫並設置錯誤模式。 2)通過prepare方法創建預處理語句,使用佔位符和execute方法傳遞數據。 3)處理查詢結果並確保代碼的安全性和性能。

See all articles

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

AI Hentai Generator

AI Hentai Generator

免費產生 AI 無盡。

熱門文章

R.E.P.O.能量晶體解釋及其做什麼(黃色晶體)
4 週前By尊渡假赌尊渡假赌尊渡假赌
R.E.P.O.最佳圖形設置
4 週前By尊渡假赌尊渡假赌尊渡假赌
R.E.P.O.如果您聽不到任何人,如何修復音頻
4 週前By尊渡假赌尊渡假赌尊渡假赌
R.E.P.O.聊天命令以及如何使用它們
4 週前By尊渡假赌尊渡假赌尊渡假赌

熱工具

DVWA

DVWA

Damn Vulnerable Web App (DVWA) 是一個PHP/MySQL的Web應用程序,非常容易受到攻擊。它的主要目標是成為安全專業人員在合法環境中測試自己的技能和工具的輔助工具,幫助Web開發人員更好地理解保護網路應用程式的過程,並幫助教師/學生在課堂環境中教授/學習Web應用程式安全性。 DVWA的目標是透過簡單直接的介面練習一些最常見的Web漏洞,難度各不相同。請注意,該軟體中

SublimeText3漢化版

SublimeText3漢化版

中文版,非常好用

MantisBT

MantisBT

Mantis是一個易於部署的基於Web的缺陷追蹤工具,用於幫助產品缺陷追蹤。它需要PHP、MySQL和一個Web伺服器。請查看我們的演示和託管服務。

SublimeText3 英文版

SublimeText3 英文版

推薦:為Win版本,支援程式碼提示!

mPDF

mPDF

mPDF是一個PHP庫,可以從UTF-8編碼的HTML產生PDF檔案。原作者Ian Back編寫mPDF以從他的網站上「即時」輸出PDF文件,並處理不同的語言。與原始腳本如HTML2FPDF相比,它的速度較慢,並且在使用Unicode字體時產生的檔案較大,但支援CSS樣式等,並進行了大量增強。支援幾乎所有語言,包括RTL(阿拉伯語和希伯來語)和CJK(中日韓)。支援嵌套的區塊級元素(如P、DIV),