Using WordPress ‘add_meta()’ PHP function

The add_meta() WordPress PHP function adds post meta data for a specified post. This metadata is derived from the $_POST superglobal for a post with a given ID.

Usage

To use the add_meta() function, you simply need to provide the post ID as the argument.

add_meta($post_ID);

In this example, $post_ID is the ID of the post for which you want to add metadata.

Parameters

  • $post_id (int): This is the ID of the post where the metadata will be added.

More information

See WordPress Developer Resources: add_meta()

Please note, unless you’ve developed a custom post form that uses the custom field widget, there is little reason to use this function.

Examples

Adding Metadata to a Post

The following example shows how to use add_meta() to add metadata to a post with an ID of 123.

$post_ID = 123;
add_meta($post_ID);

In this case, metadata from the $_POST superglobal is added to the post with an ID of 123.

Adding Metadata to the Most Recent Post

If you want to add metadata to the most recent post, you could do this:

$recent_posts = wp_get_recent_posts(array('numberposts' => 1)); 
$post_ID = $recent_posts[0]['ID'];
add_meta($post_ID);

Here, we first fetch the most recent post and then add metadata to it.

Adding Metadata After Creating a New Post

You can also add metadata right after creating a new post:

$new_post = array(
  'post_title'    => 'My New Post',
  'post_content'  => 'Hello world!',
  'post_status'   => 'publish',
);
$post_ID = wp_insert_post($new_post);
add_meta($post_ID);

After inserting a new post, we grab the ID of the newly created post and add metadata to it.

Adding Metadata to a Random Post

If you want to add metadata to a random post, this is how you could do it:

$args = array(
  'posts_per_page' => 1,
  'orderby'        => 'rand'
);
$random_post = get_posts($args);
$post_ID = $random_post[0]->ID;
add_meta($post_ID);

This code fetches a random post and adds metadata to it.

Adding Metadata to All Posts

Finally, if you want to add metadata to all posts, use a loop:

$args = array(
  'numberposts' => -1,
);
$all_posts = get_posts($args);
foreach($all_posts as $post){
  $post_ID = $post->ID;
  add_meta($post_ID);
}

This code fetches all the posts and adds metadata to each of them.