0
0
Wordpressframework~5 mins

Post meta basics in Wordpress

Choose your learning style9 modes available
Introduction

Post meta lets you store extra information about a post in WordPress. It helps you add custom details beyond the main content.

You want to save an author's nickname separately from the main author field.
You need to store a product price on a product post.
You want to add a custom date or location to an event post.
You want to save user ratings or votes on a post.
You want to keep track of a post's special status or flag.
Syntax
Wordpress
add_post_meta($post_id, $meta_key, $meta_value, $unique = false);

get_post_meta($post_id, $meta_key, $single = false);

update_post_meta($post_id, $meta_key, $meta_value, $prev_value = '');

delete_post_meta($post_id, $meta_key, $meta_value = '');

$post_id is the ID of the post you want to add or get meta for.

$meta_key is the name of the meta field, like 'price' or 'rating'.

Examples
Adds a meta field named 'color' with value 'blue' to post ID 123.
Wordpress
add_post_meta(123, 'color', 'blue');
Gets the single value of 'color' meta for post 123.
Wordpress
$color = get_post_meta(123, 'color', true);
Changes the 'color' meta value to 'red' for post 123.
Wordpress
update_post_meta(123, 'color', 'red');
Removes the 'color' meta field from post 123.
Wordpress
delete_post_meta(123, 'color');
Sample Program

This example shows how to add, get, update, and optionally delete a post meta field called 'rating' for post ID 10. It prints the original, current, and updated rating values.

Wordpress
<?php
// Add a custom meta field 'rating' with value 5 to post ID 10
add_post_meta(10, 'rating', 5, true);

// Get the 'rating' meta value
$rating = get_post_meta(10, 'rating', true);

// Update the 'rating' to 8
update_post_meta(10, 'rating', 8);

// Get the updated 'rating'
$updated_rating = get_post_meta(10, 'rating', true);

// Delete the 'rating' meta
// delete_post_meta(10, 'rating');

// Output the values
echo "Original rating: 5\n";
echo "Current rating: $rating\n";
echo "Updated rating: $updated_rating\n";
OutputSuccess
Important Notes

Use add_post_meta with $unique = true to avoid duplicate meta keys.

get_post_meta returns an array if $single is false, or a single value if true.

Always sanitize and validate meta values before saving for security.

Summary

Post meta stores extra info about posts in WordPress.

Use add_post_meta, get_post_meta, update_post_meta, and delete_post_meta to manage meta.

Meta keys are like labels, and meta values hold the data.