I built a custom post type where we can find a standard textarea/tinymce generated by wp_editor() and I’m facing an issue for the saving part.

If I save the content with the following code :

update_post_meta( $post_id, $prefix.'content', $_POST['content'] );

Everything is working fine but there is no security (sanitization, validation etc…)

If I save the content with the following code :

update_post_meta( $post_id, $prefix.'content', sanitize_text_field($_POST['content']) );

I solve the security issue but I lose all the style, media etc.. in the content.

What could be a good way to save the content with all the style applied, the media inserted but including a sanitization ?

I read a bit about wp_kses() but I don’t know how I could apply a good filter. (Allowing common tags, which one should I block ? etc..)

4 s
4

In short: it is in dependence of your context, the data inside your editor.

wp_kses() is really helpful, and you can define your custom allowed HTML tags.
Alternative, you can use the default functions, like wp_kses_post or wp_kses_data.
These functions are helpful in ensuring that HTML received from the user only contains white-listed elements. See https://codex.wordpress.org/Data_Validation#HTML.2FXML_Fragments

WordPress defines much more functions to sanitize the input, see https://codex.wordpress.org/Validating_Sanitizing_and_Escaping_User_Data and https://codex.wordpress.org/Data_Validation
These pages are really helpful.

However, in your context should the wp_kses_post function, the right choice.

Leave a Reply

Your email address will not be published. Required fields are marked *