Casi
Casi

Reputation: 123

How to sanitize text field with html in wordpress

Hi my question is how to properly sanitize input field that contains html. Now I do:

if( isset( $_POST[ 'obecnie' ] ) ) { update_post_meta( $post_id, 'obecnie', sanitize_text_field($_POST['obecnie' ])); }

sanitize_text_field is a Wordpress function and it strips all html from input. What I need to achive is actually to allow user insert break tag or new line entity in input and display this in frontend.

Upvotes: 1

Views: 6102

Answers (2)

Dave Ross
Dave Ross

Reputation: 3491

wp_kses strips HTML tags and attributes from a string except the ones you whitelist when you call it.

For example to only allow br tags and links with an href attribute (but no others, not even a style or title), you'd call it like:

$allowed_html = array(
  'a' => array(
    'href' => array(),
  ),
  'br' => array(),
);
$str = wp_kses( $str, $allowed_html );

Upvotes: 8

Not sure about that wordpress function, but you can try this function sanitize htmlentities :

 htmlentities($_POST['obecnie' ]);

And then you can convert the user entered line breaks (actual line breaks, not BR tag), to BR tag before displaying anywhere, like this :

preg_replace('/[\n\r]/', '<br />',htmlentities($_POST['obecnie' ]));

And you also need to remember to revert the line breaks back if you are going to give the user edit option:

$textToBeShownInTextBox = str_replace('<br />',"\n", $textFromDb);

Upvotes: 0

Related Questions