The best way to sanitize text fields within WordPress is to use sanitize_text_field()
function:
$data = sanitize_text_field( $_POST['key'] );
Additionally, if you register the meta field properly width register_meta()
function, you can define the sanitize callback and the expected data type as well. For example:
add_action( 'init', 'cyb_register_meta_fields' );
function cyb_register_meta_fields() {
$args = array(
'sanitize_callback' => 'sanitize_text_field'
);
register_meta( 'post', 'key', $args );
}
By using register_meta()
you don’t need to sanitize the meta field every time you upadate or create it, just use upadate_post_meta()
/add_post_meta()
and the sanitize callback will be used automatically. So, if your meta field is an array, it could be something like this:
add_action( 'init', 'cyb_register_meta_fields' );
function cyb_register_meta_fields() {
$args = array(
'sanitize_callback' => 'sanitize_price_field'
);
register_meta( 'post', 'price_data', $args );
}
function sanitize_price_field( $meta_value ) {
foreach ( (array) $meta_value as $k => $v ) {
if ( is_array( $v ) ) {
$meta_value[$k] = sanitize_price_field( $v );
} else {
$meta_value[$k] = sanitize_text_field( $v );
}
}
return $meta_value;
}