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' ]));
}

Read More

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.

Related posts

2 comments

  1. 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 );
    
  2. 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('/[nr]/', '<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);
    

Comments are closed.