I have added a meta field for text input. I want to allow some html tags such as <strong>
and <i>
For example: <strong>hello</strong> world
I can save the input field value without sanitizing and its no problem this way:
if( isset( $_POST['my_field'] ) ){
update_post_meta($post->ID, 'my_field', $_POST['my_field']);
}
However if I use the sanitize_text_field
function as following, it will remove the html tags when saving:
if( isset( $_POST['my_field'] ) ){
update_post_meta($post->ID, 'my_field', sanitize_text_field($_POST['my_field']));
}
What would be the best way to sanitize values with html tags in it before storing?
HTML in custom fields is, from my point of view, a weird use case of custom fields. Even more if the purpose of the used HTML is just look and feel (<strong>
and <i>
can be seen as just look and feel). It is really better if you use the HTML markup on the custom field output or if you use CSS to apply bold/italic styles.
That being said, you can try to use PHP strip_tags()
function or wp_kses()
function. Both allow you to strip HTML tags but allow some of them. Example using wp_kses()
:
$allowed_html = array(
'i' => array(),
'strong' => array(),
);
if( isset( $_POST['my_field'] ) ){
$meta_value = wp_kses( $_POST['my_field'], $allowed_html );
update_post_meta( $post->ID, 'my_field', $meta_value );
}