Saving meta data with WordPress.

Saving meta data with WordPress.

In this tutorial we will look at how to save meta data in WordPress.

So in your functions file, create your meta box.

Code example.
add_meta_box('My Box', 'My Box', 'meta_box', 'post', 'advanced', 'default');
function meta_box(){
?>
<input type='text' name='uniqueid' />
<?php
}

The above code is a very simple way to add a meta box to a post, if you have a custom post type, simply change the post to the id of your post type or change post to a page to add the meta box to the page editor.

In the meta_box function I have added in a single input box, this is the input we will be saving. I have set the name of the input box to uniqueid just to show that the input name must be unique.

Ok, now to save the data simply add the following code into your functions file.

Code example.
function feature_save_meta_box( $post_id, $post ) {
global $post, $type; $post = get_post( $post_id );
if( $post->post_type == 'revision' )
return; if( !current_user_can( 'edit_post', $post_id ))
return; $curdata = $_POST['uniqueid'];
$olddata = get_post_meta( $post_id, "optname", true ); if( $olddata == "" && $curdata != "" )
add_post_meta( $post_id, "optname", $curdata );
elseif( $curdata != $olddata )
update_post_meta( $post_id, "optname", $curdata); }
add_action( 'save_post', 'feature_save_meta_box', 1, 2 );

You can set the above post_meta to anything you want, just make sure it is unique to any other post meta that might be saved.

In the above I directly save the data to a post_meta, you could alternatively save it to an array and save the array to the post meta.

So in the above code we get the input field content using the $_POST method, this then gets added to a variable called $curdata, we check if this data is new by getting the old data with the get_post_meta function, if new then update post meta or if post meta does not exist, then create a new post meta type.

The top of the function is used to prevent revisions saving this data, you can remove this code if you want.

We got the post id with the global $post, this is seen at the top of the function.

Ok next we need to show the content.

So copy the above code into the meta_box function we first created:

Code example.
function meta_box(){
$content = get_post_meta( $_GET['post'], "optname", true ); ?> <input type='text' name='uniqueid' value='<?php echo $content; ?>' /> <?php }

So we get the content with the get_post_meta function and we save that to the $content variable.

We then print this variable into the value of the input box.

 

comments powered by Disqus