admin管理员组

文章数量:1122832

I have a meta field which gets displaed in the admin panel look like:

$field = get_post_meta($postid, 'field_name', true); ?>
<input type="text" name="field_name" value="<?php echo (!empty($field)) ? $field : ''; ?>" />

And usually whenever I save these sorts of things I use sanitize_text_field() which I thought that was enough, until today... Today I realized that it doesn't properly encode any html entities, such as quotations. For example: Say the user enters into my text field

Matt said "Jet fuel can't melt steel beams..."

Which can be sanitized using the function above but whenever echo'ed back out to the user I get

Matt said

The input looks like:

<input type="text" name="field_name" value="Matt said " Jet fuel can't melt steel beams" />

I can use htmlspecialchars() whenever saving my meta but then that defeats the purpose. Why would I ever use sanitize_text_field() over strip_tags( htmlspecialchars() ) ?

I have a meta field which gets displaed in the admin panel look like:

$field = get_post_meta($postid, 'field_name', true); ?>
<input type="text" name="field_name" value="<?php echo (!empty($field)) ? $field : ''; ?>" />

And usually whenever I save these sorts of things I use sanitize_text_field() which I thought that was enough, until today... Today I realized that it doesn't properly encode any html entities, such as quotations. For example: Say the user enters into my text field

Matt said "Jet fuel can't melt steel beams..."

Which can be sanitized using the function above but whenever echo'ed back out to the user I get

Matt said

The input looks like:

<input type="text" name="field_name" value="Matt said " Jet fuel can't melt steel beams" />

I can use htmlspecialchars() whenever saving my meta but then that defeats the purpose. Why would I ever use sanitize_text_field() over strip_tags( htmlspecialchars() ) ?

Share Improve this question asked Apr 20, 2015 at 23:45 DerpDerp 1713 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 0

You need to escape data while displaying also. Use esc_attr in your case. Try this:

<input type="text" name="field_name" value="<?php echo (!empty($field)) ? esc_attr( $field ) : ''; ?>" />

Check this for full documentation - https://codex.wordpress.org/Data_Validation

本文标签: validationProper Way to Sanitize Meta Input