add meta key and meta value to post in wordpress programmatically
15,706
It's possible to add custom meta data in WordPress pragmatically using add_post_meta function
add_post_meta($post_id, $meta_key, $meta_value, $unique);
For example if you want to add meta data with key name age
and value 25
to post with id 10
then you can do it like
<?php add_post_meta(10, 'age', 25); ?>
In above example, a meta key with age
and value with 25
will be added to the post id 10
and also you can use it in your template using get_post_meta function like
<?php $age = get_post_meta(10, 'age', true); ?>
Above line of code will get age
meta value from post id 10, which is 25
, so you can print it in the template as
<?php echo $age; // 25 ?>
Update:
Just add this in your functions.php
add_action('wp_insert_post', 'my_add_custom_fields');
function my_add_custom_fields($post_id)
{
if ( $_POST['post_type'] == 'your_post_type' ) {
add_post_meta($post_id, 'my_meta_key_name', 'my meta value', true);
}
return true;
}
Related videos on Youtube
Author by
rjx44
Updated on September 16, 2022Comments
-
rjx44 over 1 year
Is it possible to add custom meta key and meta value in wordpress post from a custom post type? I've tried to research everything in google but still no luck. Do you have any ideas guys? thanks
-
rjx44 over 11 yearstnx for the respond. but i want to do it in another way. i want all of the post would be added every time the user make a post in admin area.