post meta - Saving html into postmeta without stripping tags - safe?

admin2025-06-06  3

I have a product description box, I want to add the HTML from the description as postmeta, for some outside reasons I can't unescape the code coming back out of post meta.

Is it safe to just update_post_meta with raw HTML?

I have looked into wp_kses but that requires me to give it a list of allow tags, I don't have this.

I have a product description box, I want to add the HTML from the description as postmeta, for some outside reasons I can't unescape the code coming back out of post meta.

Is it safe to just update_post_meta with raw HTML?

I have looked into wp_kses but that requires me to give it a list of allow tags, I don't have this.

Share Improve this question asked Nov 23, 2018 at 15:31 SteveoSteveo 296 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 2

HTML is perfectly safe in the database. As long as you're using update_post_meta() or add_post_meta(), and not SQL directly, WordPress will make sure that you're safe from any SQL issues.

The real trouble with allowing HTML in meta is that if you are outputting this HTML on the front-end without escaping, then any user that has access to set a product description will be able to output scripts on the front end by including them in the HTML. These could potentially be malicious.

So what you can do is:

  • If the user is trusted (i.e. has the unfiltered_html capability), let them save any HTML they like.
  • If they are not, strip unsafe tags.

wp_kses() is the function for stripping disallowed HTML tags from text. You're right that you would normally need to provide a full list of tags that are allowed, but there is another function, wp_kses_post(). This function uses wp_kses(), but with a preset list of tags that WordPress allows for post authors without unfiltered_html (Authors and Contributors).

So in practice this would look like:

$description = $_POST['description'];

if ( current_user_can( 'unfiltered_html' ) ) {
    update_post_meta( $post_id, 'description', $description );
} else {
    update_post_meta( $post_id, 'description', wp_kses_post( $description ) );
}
转载请注明原文地址:http://conceptsofalgorithm.com/Algorithm/1749154736a316831.html

最新回复(0)