Created
July 1, 2016 12:45
Star
You must be signed in to star a gist
[WordPress] Using wp_kses for custom data validation in WordPress.
This file contains 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 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 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