Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

add meta key and meta value to post in wordpress programmatically

Tags:

wordpress

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

like image 475
rjx44 Avatar asked Dec 15 '22 19:12

rjx44


1 Answers

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;
}
like image 56
The Alpha Avatar answered Jan 25 '23 23:01

The Alpha