Advanced WordPress Development

Master advanced WordPress development including REST API, Gutenberg, and performance optimization.

advanced Backend Development 6 hours

Chapter 12: Custom Fields and Meta Boxes

Chapter 12 of 15

Chapter 12: Custom Fields and Meta Boxes

12.1 Custom Fields Overview

Add custom data to posts using custom fields.

// Add custom field
add_post_meta($post_id, 'custom_field', 'value');

// Get custom field
$value = get_post_meta($post_id, 'custom_field', true);

// Update custom field
update_post_meta($post_id, 'custom_field', 'new_value');

12.2 Creating Meta Boxes

Create custom meta boxes for post editing.

// Add meta box
add_action('add_meta_boxes', 'add_custom_meta_box');

function add_custom_meta_box() {
    add_meta_box(
        'custom_meta_box',
        'Custom Meta Box',
        'custom_meta_box_callback',
        'post'
    );
}

function custom_meta_box_callback($post) {
    wp_nonce_field('save_custom_meta', 'custom_meta_nonce');
    $value = get_post_meta($post->ID, 'custom_field', true);
    echo '<input type="text" name="custom_field" value="' . esc_attr($value) . '">';
}

12.3 Saving Meta Box Data

Save meta box data when post is saved.

add_action('save_post', 'save_custom_meta_box');

function save_custom_meta_box($post_id) {
    if (!isset($_POST['custom_meta_nonce']) || 
        !wp_verify_nonce($_POST['custom_meta_nonce'], 'save_custom_meta')) {
        return;
    }
    
    if (isset($_POST['custom_field'])) {
        update_post_meta($post_id, 'custom_field', sanitize_text_field($_POST['custom_field']));
    }
}

12.4 Advanced Custom Fields (ACF)

Use ACF plugin for advanced custom fields.

  • Visual field builder
  • Multiple field types
  • Conditional logic
  • Repeater fields
  • Flexible content fields

12.5 Custom Fields Best Practices

Follow best practices for custom fields.

  • Use descriptive field names
  • Sanitize and validate input
  • Use appropriate field types
  • Document custom fields
  • Consider performance impact