Created
July 1, 2016 12:45
-
-
Save tommcfarlin/2a7a29d1e6fc7980559a7299db130af6 to your computer and use it in GitHub Desktop.
[WordPress] Using wp_kses for custom data validation in WordPress.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <?php | |
| /** | |
| * For this example, we're not worried with i18n nor the function calls needed | |
| * to set variables like $pages. Assume that the pages are pulled earlier in the | |
| * lifecycle of the program. | |
| * | |
| * There are other places in which you may want to validate information, but the purposes of | |
| * this example is ultimately to highlight how to customize the allowed HTML via wp_kses. | |
| */ | |
| $html = '<select>'; | |
| $html .= '<option>Select a page...</option>'; | |
| foreach ( $pages as $page ) { | |
| $html .= '<option>'; | |
| $html .= $page->post_title; | |
| $html .= '</option>'; | |
| } | |
| $html .= '</select>'; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <?php | |
| /** | |
| * We're going to allow the select element to have a name attribute | |
| * and allow the option elements to have both a value and selected | |
| * attribute. | |
| */ | |
| $allowed_html = array( | |
| 'select' => array( | |
| 'name' => array(), | |
| ), | |
| 'option' => array( | |
| 'value' => array(), | |
| 'selected' => array(), | |
| ), | |
| ); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <?php | |
| $html = '<select name="acme[page]">'; | |
| $html .= '<option value="default">Select a page...</option>'; | |
| foreach ( $pages as $page ) { | |
| /** | |
| * Set a $selected variable here using a custom function or using | |
| * WordPress' selected() helper. | |
| */ | |
| $html .= '<option value="' . $page->ID . '"' . $selected . '>'; | |
| $html .= $page->post_title; | |
| $html .= '</option>'; | |
| } | |
| $html .= '</select>'; | |
| $allowed_html = array( | |
| 'select' => array( | |
| 'name' => array(), | |
| ), | |
| 'option' => array( | |
| 'value' => array(), | |
| 'selected' => array(), | |
| ), | |
| ); | |
| echo wp_kses( $html, $allowed_html ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment