WordPress provides filters for sanitizing and authenticating your custom post meta. These filters have been around since 3.3 — and until now — were unknown to me. I happened to be reading Tadlock’s content-type-standards repository on Github and noticed some references to register_meta().
What Is register_meta?
The register_meta() function was added in WordPress 3.3 and will simplify adding sanitize and authentication callbacks for your custom meta. By calling this function and providing callbacks, it will handle appending your callbacks to the appropriate filters.
Let’s take a look at the function.
The function has four parameters; One being optional.
- $meta_type This is the type of meta. Most of the time this will be ‘post’, unless you are working with a custom meta table.
- $meta_key Exactly as it sounds. Your meta key.
- $sanitize_callback The sanitize callback. The meta value will run through the sanitize callback function before saving.
- $auth_callback If provided, the meta will be hidden from Custom Fields meta box with the post editor. This has the same affect as pre-pending the meta key name with an underscore.
Here is a simple example for registering a meta key.
Simply calling register_meta() within a callback for ‘init’ will suffice. My sample meta key will be ‘sample_count’. Simple enough.
The Sanitize Callback
I wish I had knowledge of this filter as it would have saved me time. If you save post meta in more than one place, there is a good chance you have duplicate code. Using this filter allows meta value to be sanitized in once place and reduce that sneaky duplicate code.
I am just simply running the meta value through absint().
The Authentication Callback
In WordPress, you can pre-pend your meta keys with an underscore to prevent them from being visible within the Custom Fields meta box. This prevents all users from the ability to see the meta values in the Custom Fields meta box.
This callback determines who sees what within the Custom Fields meta box. This allows your meta keys to not have the pre-pended underscore. My example allows administrators to see the meta value.
Remember, this is optional.
All Together Now
Here is the full example. The sanitize callback is what I find to be the biggest advantage here. The custom authentication is purely up to you.