📦 Store Extra Data with Posts
Posts need extra data. Custom fields (post meta) store additional information. Product price, event date, author bio.
📝 Using Custom Fields
// Add custom field
add_post_meta($post_id, 'product_price', 99.99, true);
// Update custom field
update_post_meta($post_id, 'product_price', 89.99);
// Get custom field
$price = get_post_meta($post_id, 'product_price', true);
// Get all custom fields
$all_meta = get_post_meta($post_id);
// Delete custom field
delete_post_meta($post_id, 'product_price');
// Check if meta exists
if (metadata_exists('post', $post_id, 'product_price')) {
// Meta exists
}
// For arrays and objects (serialize)
update_post_meta($post_id, 'settings', array(
'color' => 'blue',
'size' => 'large'
));
🎯 Real-World Examples
// Product fields
add_post_meta($product_id, '_price', 49.99);
add_post_meta($product_id, '_sku', 'PROD-001');
add_post_meta($product_id, '_stock', 100);
// Event fields
add_post_meta($event_id, '_event_date', '2024-12-25');
add_post_meta($event_id, '_event_location', 'Convention Center');
add_post_meta($event_id, '_event_seats', 500);
// User fields (user meta)
add_user_meta($user_id, 'twitter', '@username');
add_user_meta($user_id, 'birthday', '1990-01-01');
// Display in template
$price = get_post_meta(get_the_ID(), '_price', true);
if ($price) {
echo '<p>Price: $' . number_format($price, 2) . '</p>';
}
💡 Advanced Features
- ACF (Advanced Custom Fields) plugin for UI
- Custom meta boxes for admin
- Meta query for searching by custom fields
- Use with WP_Query for filtering
“Custom fields stored product prices and SKUs. Now products have structured data. Essential for e-commerce.”
