Skip to content

Instantly share code, notes, and snippets.

@tommcfarlin
Created July 1, 2016 12:45
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save tommcfarlin/2a7a29d1e6fc7980559a7299db130af6 to your computer and use it in GitHub Desktop.
[WordPress] Using wp_kses for custom data validation in WordPress.
<?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>';
<?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(),
),
);
<?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