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
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With