WordPress Settings API 指南:驗證、過濾和輸入(二)

本文是《WordPress Settings API 指南》專題的第 8 篇,共 8 篇:

本文就是這個系類的最后一篇了,在上一篇文章,我們了解了 驗證、安全過濾(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:

1
2
3
4
5
6
7
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:

1
2
3
4
5
6
7
8
9
10
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:

1
$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:

1
$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:

1
2
3
4
5
<?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:

1
2
3
4
5
6
7
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:

1
2
3
4
5
6
7
8
9
10
11
12
13
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:

1
2
3
4
5
<?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:

1
2
3
4
5
6
7
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:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
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:

1
2
3
4
5
6
7
<?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

聲明:本站所有文章,如無特殊說明或標注,均為本站原創發布。任何個人或組織,在未征得本站同意時,禁止復制、盜用、采集、發布本站內容到任何網站、書籍等各類媒體平臺。如若本站內容侵犯了原著者的合法權益,可聯系我們進行處理。
歡迎關注我們的微信公眾號:WPDAXUE

倡萌

一個文科IT宅男,喜歡折騰WordPress和被它折騰 ^_^

暫無評論

發表評論