外贸独立站的底层设计密码WordPress 成品站模板
当前位置:首页>WordPress建站>WordPress开发>WordPress Settings API 指南:验证、过滤和输入(二)

WordPress Settings API 指南:验证、过滤和输入(二)

本文就是这个系类的最后一篇了,在上一篇文章,我们了解了 验证、安全过滤(sanitization)和一些基本的输入元素,以便我们可以更方便地创建设置页面。

文本将一起来看下最后一组的3个选项,看看如何挂载它们到主题的前端。

注:由于时间精力有限,本教程没办法翻译分享,希望朋友们可以加入我们,帮助我们进行翻译,有小酬谢,有意者请联系倡萌QQ 745722006(注明:教程翻译)。

以下为原文:http://code.tutsplus.com/tutorials/the-complete-guide-to-the-wordpress-settings-api-part-8-validation-sanitisation-and-input-ii–wp-25361

We’ve reached the final article of the series. In the last post, we took a look at introducing validation, sanitization, and a couple of basic input elements that we can take advantage of when building option pages.

In this article, we’re going to take a look at the final set of three options and how to hook them up to the front-end of the theme.

Before we get started: As with the last few, this article assumes that you’ve been following along with the rest of the series, have a working copy of the sample code installed, and are now relatively familiar with the Settings API and theme options. If you’re uncertain about any of the above, I highly recommend reading the rest of the articles before diving into this post.

The Element Types, Continued

Checkbox

Earlier in this series, we added checkboxes. We could go back and revisit those, but let’s keep consistent with what we’ve done up to this point and introduce new options. Once we’re done, you can revisit the code we added at the beginning of the series for review.

First, let’s introduce the checkbox element to the sandbox_theme_initialize_input_examples function:

add_settings_field(
    'Checkbox Element',
    'Checkbox Element',
    'sandbox_checkbox_element_callback',
    'sandbox_theme_input_examples',
    'input_examples_section'
);

Next, we need to go ahead and define the callback that we’ve specified above. Add the following function to your project:

function sandbox_checkbox_element_callback() {
 
    $options = get_option( 'sandbox_theme_input_examples' );
     
    $html = '<input type="checkbox" id="checkbox_example" name="sandbox_theme_input_examples[checkbox_example]" />';
    $html .= '<label for="checkbox_example">This is an example of a checkbox</label>';
     
    echo $html;
 
} // end sandbox_checkbox_element_callback

We’ll be revisiting this function momentarily, but first notice that I’ve added a label element next to the checkbox. Checkboxes often have an element associated with them that also afford the ability to be clicked to trigger the checkbox. This makes it easier for users to toggle an option without having to click precisely in the checkbox.

To associate a label with a checkbox, you need to give the label’s for attribute the value of the ID attribute of the checkbox to which it is bound. Easy enough, right?

Now, refresh your options page and you should see the new element visible on your options page. But, for now, it doesn’t actually save or retrieve a value. First, let’s introduce a value attribute on the checkbox. This is somewhat arbitrary but it’s a common practice to give a checked element a value of ‘1.’ Let’s do that now:

$html = '<input type="checkbox" id="checkbox_example" name="sandbox_theme_input_examples[checkbox_example]" value="1" />';

Next, let’s think through exactly what needs to happen when we save a value. Ideally:

  • The user checks the element and saves the value
  • The page refreshes and the checkbox is checked
  • The user checks the element to disable it and saves the value
  • The page refreshes and the checkbox is not checked

Relatively clear, right? Rather than reading the option, setting up a conditional, and checking for the presence or absence of a value, we can take advantage of WordPress’ checked function.

The function accepts three arguments, only the first of which is required:

  1. The first value is one of the values to compare
  2. The second value to compare if the first value is not true
  3. Whether or not to echo check="checked" to the browser

So let’s update our code to use this function:

$html = '<input type="checkbox" id="checkbox_example" name="sandbox_theme_input_examples[checkbox_example]" value="1"' . checked( 1, $options['checkbox_example'], false ) . '/>';

Refresh the page and check the option, save, and repeat.

If any of this looks a bit confusing, review the previous article where we cover the significances of each attribute on an option element.

Finally, let’s update the front end of the theme to check this option and render a string of text based on if the option has been checked. Recall that when we created the element, we gave it the value of ‘1‘. This means that when the checkbox is checked and serialized, it will maintain a value of one. Simply put, we need to write a conditional that checks the value of the option and then renders text appropriately. Inindex.php, add this block of code:

<?php if( $input_examples['checkbox_example'] == '1' ) { ?>
    <p>The checkbox has been checked.</p>
<?php } else { ?>
    <p>The checkbox has not been checked.</p>
<?php } // end if ?>

Now, go back to your settings page, toggle the checkbox, and refresh your page.

As mentioned at the beginning of this section, look back at the ‘Display Options’ that we introduced earlier in this series and see if it’s much clearer now that we’ve examined how to introduce and manage checkbox elements.

Radio Buttons

Radio Buttons are elements that are useful in groups – after all, you’re never going to use a single radio button. The thing about radio elements is that they provide a way to allow users to choose one out of a mutually exclusive set of options.

For one reason or another, radio buttons are often a challenge for WordPress developers. Hopefully, we’ll make it as easy as possible to bring into our projects. As with the rest of the examples in this series, detail what we’re going to do:

  • We want to introduce two options from which the user must select. We’ll be giving them very general labels.
  • The first option will be a radio element with the label ‘Option One’ and will have the value of ‘1’.
  • The second option will be a radio element with the label ‘Option Two’ and will have the value of ‘2’.

Seems clear enough – let’s go ahead and add the field element to our options page:

add_settings_field(
    'Radio Button Elements',
    'Radio Button Elements',
    'sandbox_radio_element_callback',
    'sandbox_theme_input_examples',
    'input_examples_section'
);

And let’s implement the radio element’s callback. First, we’ll specify the code, then we’ll review it:

function sandbox_radio_element_callback() {
 
    $options = get_option( 'sandbox_theme_input_examples' );
     
    $html = '<input type="radio" id="radio_example_one" name="sandbox_theme_input_examples[radio_example]" value="1"' . checked( 1, $options['radio_example'], false ) . '/>';
    $html .= '<label for="radio_example_one">Option One</label>';
     
    $html .= '<input type="radio" id="radio_example_two" name="sandbox_theme_input_examples[radio_example]" value="2"' . checked( 2, $options['radio_example'], false ) . '/>';
    $html .= '<label for="radio_example_two">Option Two</label>';
     
    echo $html;
 
} // end sandbox_radio_element_callback

The first thing to notice when working with radio buttons is that they do not follow the typical examples of how to set the ID and name attributes. Notice that the ID attribute is unique and has no relationship to the rest of the attributes on the element. Also notice that each element’s associated label uses the ID for it’sfor attribute. This binds the label to the radio button so that users can click on the label to select the radio element.

Next, notice that the name attributes are the same for each radio element but the values are different. This is what makes radio buttons mutually exclusive – each radio element needs to have the same name but the values must be unique.

Finally, we can set up a conditional on the homepage by checking the element’s value. In your theme’sfunctions.php, add the following block of code:

<?php if( $input_examples['radio_example'] == 1 ) { ?>
    <p>The first option was selected.</p>
<?php } elseif( $input_examples['radio_example'] == 2 ) { ?>
    <p>The second option was selected.</p>
<?php } // end if  ?>

Load your theme’s homepage, toggle the options, and refresh. You should see the two sentences changing based on the value of the option elements.

Select Box

The last element that we’re going to review is the select element. This element gives users a drop-down menu of options from which to choose. Let’s plan out exactly what we need to introduce for this element:

  • Define a select element. In our example, we’ll be treating it as three options for time.
  • We’ll give the options for ‘Never’, ‘Sometimes’, and ‘Always’.
  • We’ll populate a default option that will be set when the page loads.

At this point in the series, this should be quite routine. Let’s get started – first, we’ll introduce the settings field:

add_settings_field(
    'Select Element',
    'Select Element',
    'sandbox_select_element_callback',
    'sandbox_theme_input_examples',
    'input_examples_section'
);

Next, we’ll define the callback function. Review the code and then we’ll discuss it after the example:

function sandbox_select_element_callback() {
 
    $options = get_option( 'sandbox_theme_input_examples' );
     
    $html = '<select id="time_options" name="sandbox_theme_input_examples[time_options]">';
        $html .= '<option value="default">Select a time option...</option>';
        $html .= '<option value="never"' . selected( $options['time_options'], 'never', false) . '>Never</option>';
        $html .= '<option value="sometimes"' . selected( $options['time_options'], 'sometimes', false) . '>Sometimes</option>';
        $html .= '<option value="always"' . selected( $options['time_options'], 'always', false) . '>Always</option>';
    $html .= '</select>';
     
    echo $html;
 
} // end sandbox_radio_element_callback

First, refresh your options page to make sure the select element appears. Assuming that it does, let’s review the code above.

When defining the select element, we’ve given it an ID attribute and a name attribute much as we do with the rest of the elements that we’ve demonstrated. Next, each option has a unique value and text that corresponds to the value. Though you don’t have to do this, I’ve typically found it helpful when working in my projects. Finally, we’ve taken advantage of the selected helper that WordPress offers. This is much like the checked function that we’ve used in previous example except that it’s geared towards select options.

The last step will be to update the front end of the theme so that it checks the value of the select element after it has been saved. Add the following block of code to your index.php:

<?php if( $input_examples['time_options'] == 'never' ) { ?>
    <p>Never display this. Somewhat ironic to even show this.</p>
<?php } elseif( $input_examples['time_options'] == 'sometimes' ) { ?>
    <p>Sometimes display this.</p>
<?php } elseif( $input_examples['time_options'] == 'always' ) { ?>
    <p>Always display this.</p>
<?php } // end if/else ?>

Revisit the homepage of your theme, change up the options, and then refresh the page – you should notice the text update based on the option that you’ve selected.

Conclusion

With that, we finally reach the end of this series. The Settings API is a powerful feature of WordPress and provides us with the ability to implement well-designed, secure option pages, but it requires that we use it properly. Unfortunately, this is probably one of the most ignored features of the platform by many developers.

Ultimately, my goal was to walk developers through the API from the very beginning of understanding why it’s important, to settings, from menu pages, to tabbed navigation, and how to work with each of the element types.

Finally, remember that you can find the example code on GitHub. As you continue to work with the Settings API or find a feature that’s unclear, please contribute. I’d love for this series and the example code to continue to provide a source of education for the WordPress community.

Related Sources

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。

给TA打赏
共{{data.count}}人
人已打赏
欢迎关注WordPress大学公众号 WPDAXUE
WordPress开发

WordPress Settings API 指南:验证、过滤和输入(一)

2016-6-15 7:48:00

WordPress开发

WordPress HTTP API 指南:wp_remote_get 概述

2016-6-16 7:29:00

0 条回复 A文章作者 M管理员
    暂无讨论,说说你的看法吧
个人中心
购物车
优惠劵
今日签到
有新私信 私信列表
搜索