WordPress Q&As Logo
WordPress Q&As Part of the Q&A Network
Q&A Logo

How can I add custom fields to a post type programmatically?

Asked on Sep 18, 2025

Answer

To add custom fields to a post type programmatically in WordPress, you can use the `add_meta_box` function within your theme's `functions.php` file or a custom plugin. This function allows you to create custom meta boxes that appear on the post edit screen, where you can input additional data.
<!-- BEGIN COPY / PASTE -->
    function my_custom_meta_box() {
        add_meta_box(
            'my_meta_box_id',          // Unique ID
            'Custom Field Title',      // Box title
            'my_meta_box_callback',    // Content callback, must be of type callable
            'post'                     // Post type
        );
    }
    add_action('add_meta_boxes', 'my_custom_meta_box');

    function my_meta_box_callback($post) {
        // Add a nonce field so we can check for it later.
        wp_nonce_field('my_custom_nonce', 'my_custom_nonce_field');

        $value = get_post_meta($post->ID, '_my_meta_value_key', true);

        echo '<label for="my_custom_field">Description for this field</label>';
        echo '<input type="text" id="my_custom_field" name="my_custom_field" value="' . esc_attr($value) . '" size="25" />';
    }

    function save_my_meta_box_data($post_id) {
        if (!isset($_POST['my_custom_nonce_field'])) {
            return;
        }
        if (!wp_verify_nonce($_POST['my_custom_nonce_field'], 'my_custom_nonce')) {
            return;
        }
        if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) {
            return;
        }
        if (!current_user_can('edit_post', $post_id)) {
            return;
        }

        if (!isset($_POST['my_custom_field'])) {
            return;
        }

        $my_data = sanitize_text_field($_POST['my_custom_field']);
        update_post_meta($post_id, '_my_meta_value_key', $my_data);
    }
    add_action('save_post', 'save_my_meta_box_data');
    <!-- END COPY / PASTE -->
Additional Comment:
  • This example creates a text input field for posts, but you can customize it for other post types by changing the `'post'` parameter to your desired post type.
  • Ensure to handle data sanitization and validation to maintain security and data integrity.
  • Remember to include nonce fields for security when saving custom field data.
✅ Answered with WordPress best practices.

← Back to All Questions
The Q&A Network