WordPress update_post_meta Function And How To Use It

WordPress update_post_meta function

When you’re creating a WordPress plugin or customizing your theme, you may need to store some meta information about your posts in the database. In this article, we’re going to take a look at how to use update_post_meta function to achieve exactly that.

The update_post_meta Function Definition And Arguments

<?php

function update_post_meta(int $post_id, string $meta_key, mixed $meta_value, mixed $prev_value = '')

As you can see, the function takes 4 arguments:

  • $post_id – ID of the post associated with the meta data
  • $meta_key – name of the meta field
  • $meta_value – meta value that is to be stored
  • $prev_value – optional previous value to check before updating. If specified, only update existing metadata entries with this value. Otherwise, update all entries.

How To Use The update_post_meta Function

Let’s say we want to store how many times our post has been viewed every time someone visits a post page. Here is how we can do it.

<?php

add_action('template_redirect', function() {
  
  // Check if we're on the post page
  if (! is_singular('post')) {
    return;
  }

  global $post;
  
  // Check how many views the post already has
  $views = get_post_meta($post->ID, 'views', true);
  
  // If no views yet are stored in the database, set the value to 0
  if (empty($views)) {
    $views = 0;
  }

  update_post_meta($post->ID, 'views', $views + 1);

});

As you can see, we first check if the page that is displayed is a post page. Then, we check how many views the post already has.

If it doesn’t have any yet, we set the value of the $views variable to 0. And then, we simply store the updated number of views using the update_post_meta function.

Functions Similar To update_post_meta Function

  • get_post_meta(int $post_id, string $key = ”, bool $single = false) – the get_post_meta function retrieves a meta value for a given post.
  • add_post_meta(int $post_id, string $meta_key, mixed $meta_value, bool $unique = false) – adds a custom post meta to the database
  • delete_post_meta(int $post_id, string $meta_key, mixed $meta_value = ”) – deletes a post meta value from the database.

Wrapping Up

As you can see, the update_post_meta function can be handy in some situations especially when you’re building a custom theme or plugin.

About The Author

Andriy Haydash

Andriy Haydash

Andriy Haydash is a WordPress Expert who helps people build and launch successful WordPress membership and e-learning websites.

Note: Not all of the articles are written directly by me.
Affiliate Disclaimer: Some links in the post may be my affiliate links

The Ultimate Managed Hosting Platform

Before YOU Leave...
Join My Newsletter

Get practical tips & tricks on how to start, grow and market your course/membership site.