wordpress plugin creation get_post_meta

I am building my first plugin, and I am using as a reference the following link.
http://www.sitepoint.com/create-a-voting-plugin-for-wordpress/

and I am trying to underestand the following part of the code:

Read More
function voteme_addvote()
{
    $results = '';
    global $wpdb;
    $post_ID = $_POST['postid'];
    $votemecount = get_post_meta($post_ID, '_votemecount', true) != '' ? get_post_meta($post_ID, '_votemecount', true) : '0';
    $votemecountNew = $votemecount + 1;
    update_post_meta($post_ID, '_votemecount', $votemecountNew);
    $results.='<div class="votescore" >'.$votemecountNew.'</div>';
    // Return the String
    die($results);
}

I run the code and it works, but I just dont understand the following:

  • What is “get_post_meta” doing?
  • Does it create a custom meta field, the same as add_post_meta?, if it doesnt why there is not an add_post_meta?
  • I checked the DB, and it looks like it is creating a custom meta field… so in that order what is the difference between get_post_meta and add_post_meta?

Thanks very much for helping me understand this.

Related posts

Leave a Reply

1 comment

  1. The first time your code runs, get_post_meta returns ” so $votemecount is set to 0. The following update_post_meta creates the new meta field as documented below. Values that start with _ are not displayed (are hidden meta fields).

    The function, update_post_meta(), updates the value of an existing meta key (custom field) for the specified post.

    This may be used in place of add_post_meta() function. The first thing this function will do is make sure that $meta_key already exists on $post_id. If it does not, add_post_meta($post_id, $meta_key, $meta_value) is called instead and its result is returned.