📦 Store Extra Data with Custom Fields
Posts have limited fields. Custom fields store additional data. Any data, any type — extend WordPress power.
📝 Using Custom Fields
// functions.php
function add_custom_fields() {
add_meta_box(
'product_details',
'Product Details',
'display_product_fields',
'product',
'normal',
'high'
);
}
add_action('add_meta_boxes', 'add_custom_fields');
function display_product_fields($post) {
$price = get_post_meta($post->ID, '_product_price', true);
$sku = get_post_meta($post->ID, '_product_sku', true);
$stock = get_post_meta($post->ID, '_product_stock', true);
?>
🎯 Working with Custom Fields
# Get custom fields
$price = get_post_meta($post_id, '_product_price', true);
$sku = get_post_meta($post_id, '_product_sku', true);
$stock = get_post_meta($post_id, '_product_stock', true);
# Set custom fields
update_post_meta($post_id, '_product_price', 99.99);
update_post_meta($post_id, '_product_sku', 'PROD-001');
update_post_meta($post_id, '_product_stock', 50);
# Add custom field (if doesn't exist)
add_post_meta($post_id, '_product_price', 99.99, true);
# Delete custom field
delete_post_meta($post_id, '_product_price');
# Get all custom fields
$all_meta = get_post_meta($post_id);
foreach ($all_meta as $key => $value) {
echo "$key: " . $value[0] . "
";
}
# Check if field exists
$has_price = metadata_exists('post', $post_id, '_product_price');
# Query posts by custom field
$args = array(
'post_type' => 'product',
'meta_query' => array(
array(
'key' => '_product_price',
'value' => 100,
'type' => 'NUMERIC',
'compare' => '>'
)
)
);
$products = new WP_Query($args);
# Custom Field Use Cases
- Product prices, SKU, stock
- Event dates and locations
- Book ISBN, author, publisher
- User profile fields
- SEO meta data
💡 Custom Field Tips
- Product prices, SKU, stock
- Event dates and locations
- Book ISBN, author, publisher
- User profile fields
- SEO meta data
"Custom fields extend WordPress. Any data, any type. Essential for advanced WordPress development."
