WordPress Metadata API
The Metadata API in WordPress is a set of functions that allow developers to store, retrieve, update, and delete metadata for posts, users, comments, and terms. Metadata provides a flexible way to attach extra data to existing WordPress objects, beyond standard fields.
Types of Metadata
WordPress supports metadata for four core object types:
- Post Meta (
wp_postmeta
) - User Meta (
wp_usermeta
) - Comment Meta (
wp_commentmeta
) - Term Meta (
wp_termmeta
)
Each type of metadata is stored in a dedicated database table.
Core Functions
Function | Description |
---|---|
add_metadata() | Add new metadata to an object |
get_metadata() | Retrieve existing metadata |
update_metadata() | Update existing metadata |
delete_metadata() | Remove metadata from an object |
For convenience, these functions have wrapper functions like
add_post_meta()
,get_user_meta()
, etc.
Example (Post Meta):
// Add custom field (meta)
add_post_meta( $post_id, 'price', '20.00' );
// Retrieve custom field
$price = get_post_meta( $post_id, 'price', true );
// Update custom field
update_post_meta( $post_id, 'price', '25.00' );
// Delete custom field
delete_post_meta( $post_id, 'price' );
When to Use Metadata
- Custom fields (like Advanced Custom Fields – ACF)
- Additional user profile data
- Custom settings for posts or terms
- Extra information for comments or reviews
- Extending core WordPress objects
How is Metadata Stored?
- Stored as key-value pairs (similar to Options API)
- Serialized automatically if storing arrays or objects
- Easily queryable via
WP_Query
orWP_User_Query
Best Practices
- Use descriptive, prefixed meta keys (
myplugin_price
instead of justprice
) - Avoid excessive queries by caching metadata
- Limit the use of serialized data for performance reasons