I am trying to create post options for my new WordPress template, but I don’t know how I can sanitize or validate my custom post meta data before saving:
$data = $_POST['enablog_post_options'];
// Update the meta fields in the database.
update_post_meta( $post_id, 'enablog_post_options',$data );
All options (YouTube URL, text, checkbox and radio buttons) are saved with my unique meta key enablog_post_options
.
Update:
sanitize_text_field()
corrupted all my code (all checkboxes are checked when I save the post), IMHO I need more than simply sanitize_text_field()
, because $_POST['enablog_post_options']
has checkboxes, text fields and more.
First. Assuming the
$_POST['enablog_post_options']
is an array it should be sanitized as an array, iterating each one element in a loop. Not as a string, all elements at once.So look up into your
enablog_post_options
array and decide a data-type-dependent techinque of sanitizaion for each element. WP Codex can help starting with it.Now. As you understand what data types you are really going to sanitize, I suspect it is worth mentioning the
update_post_meta()
built-in sanitization actions & custom filters you can hook to the function.So, anyone can look up the code of the
update_metadata()
function that does the heavy lifting forupdate_post_meta()
here in the Core Metadata API source code.But meanwhile, it sanitizes:
sanitize_key()
andwp_unslash()
;wp_unslash()
andsanitize_meta()
(more explanation on this one follows).wpdb::prepare()
called fromupdate_metadata()
->wpdb::update()
;Sanitize with
sanitize_meta()
.The convenient way to additionally sanitize the [custom] post meta is via
sanitize_meta()
. Theupdate_metadata()
already hooks the potentially existing custom sanitization filter you have to create into the process of meta field sanitization. This is done viasanitize_meta()
.It is called from
update_metadata()
like this with all your post meta parameters:So you can just make a custom sanitization filter to work with your post meta like this (the example from WP Codex
sanitize_meta()
description, the link above):Continuing with some imagnary code, in
sanitize_birth_year_meta()
instead of$year
you will get your$data
content to get sanitized when the the filter is called.WordPress standards recommend to use
wp_unslash()
for every global variable that are ($_POST ,$_GET and etc).. after that use any sanitize function according to your need.Use this to sanitize your data:
Have a look at the Codex on Validating Sanitizing and Escaping User Data