Ask any question about WordPress here... and get an instant response.
How can I add custom fields to a WordPress post type without using a plugin? Pending Review
Asked on Dec 15, 2025
Answer
To add custom fields to a WordPress post type without using a plugin, you can utilize the `add_meta_box` function in your theme's `functions.php` file. This allows you to create custom fields that appear in the post editing screen.
<!-- BEGIN COPY / PASTE -->
function my_custom_meta_box() {
add_meta_box(
'my_meta_box_id', // Unique ID
'Custom Field Title', // Box title
'my_custom_meta_box_html', // Content callback, must be of type callable
'post' // Post type
);
}
add_action('add_meta_boxes', 'my_custom_meta_box');
function my_custom_meta_box_html($post) {
$value = get_post_meta($post->ID, '_my_meta_key', true);
?>
<label for="my_field">Description for this field</label>
<input type="text" id="my_field" name="my_field" value="<?php echo esc_attr($value); ?>" />
<?php
}
function save_my_custom_meta_box($post_id) {
if (array_key_exists('my_field', $_POST)) {
update_post_meta(
$post_id,
'_my_meta_key',
sanitize_text_field($_POST['my_field'])
);
}
}
add_action('save_post', 'save_my_custom_meta_box');
<!-- END COPY / PASTE -->Additional Comment:
- Replace 'post' with your custom post type if needed.
- Ensure you validate and sanitize input data appropriately.
- Use `esc_attr` to safely output data in HTML attributes.
- Consider using nonces for security when saving meta box data.
Recommended Links:
