Add meta key and meta value to post in wordpress programmatically

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

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

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

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;

Leave a Comment

Your email address will not be published. Required fields are marked *