How to Add Custom Field in WordPress: Simple Guide
To add a custom field in WordPress, you can use the built-in
add_post_meta() function in your theme or plugin code, or enable and use the Custom Fields meta box in the post editor to add fields manually. Custom fields let you store extra information linked to posts or pages.Syntax
The main function to add a custom field programmatically is add_post_meta(). It requires the post ID, a key (field name), and a value. Optionally, you can specify if the key should be unique.
add_post_meta($post_id, $meta_key, $meta_value, $unique);
Parameters explained:
- $post_id: The ID of the post to attach the field to.
- $meta_key: The name of the custom field.
- $meta_value: The value stored in the field.
- $unique: (Optional) Set to true to prevent duplicate keys.
php
add_post_meta($post_id, $meta_key, $meta_value, $unique = false);Example
This example shows how to add a custom field named subtitle with the value My Custom Subtitle to a post with ID 123.
php
<?php $post_id = 123; $meta_key = 'subtitle'; $meta_value = 'My Custom Subtitle'; // Add the custom field add_post_meta($post_id, $meta_key, $meta_value, true); // To retrieve and display the custom field value $subtitle = get_post_meta($post_id, $meta_key, true); echo 'Subtitle: ' . esc_html($subtitle); ?>
Output
Subtitle: My Custom Subtitle
Common Pitfalls
Common mistakes when adding custom fields include:
- Not using the correct post ID, so the field is added to the wrong post.
- Forgetting to set the
$uniqueparameter, causing duplicate fields. - Not escaping output when displaying custom field values, which can cause security issues.
- Trying to add custom fields without enabling the Custom Fields meta box in the WordPress editor (if adding manually).
php
<?php // Wrong: missing post ID or wrong ID add_post_meta(0, 'color', 'blue'); // Won't work as expected // Right: use correct post ID $post_id = 123; add_post_meta($post_id, 'color', 'blue', true); // Wrong: output without escaping echo get_post_meta($post_id, 'color', true); // Right: escape output for safety echo esc_html(get_post_meta($post_id, 'color', true)); ?>
Quick Reference
| Function | Purpose | Parameters |
|---|---|---|
| add_post_meta | Add a custom field to a post | $post_id, $meta_key, $meta_value, $unique=false |
| update_post_meta | Update existing custom field value | $post_id, $meta_key, $meta_value |
| get_post_meta | Retrieve custom field value | $post_id, $meta_key, $single=true |
| delete_post_meta | Remove a custom field | $post_id, $meta_key, $meta_value=null |
Key Takeaways
Use add_post_meta() with the correct post ID to add custom fields programmatically.
Enable the Custom Fields meta box in the post editor to add fields manually without code.
Always escape custom field output with esc_html() to keep your site secure.
Avoid duplicate keys by setting the unique parameter to true when adding fields.
Use get_post_meta() to retrieve and display custom field values safely.