Skip to content

How to save custom meta box fields on WordPress

Some weeks ago i have written about “How to add custom meta box to wordpress admin interface“, the article focused only on adding the metabox and fields on the WordPress admin interface. On this post i will guide you through how save and retrieve custom_meta fields from database.

Saving the values on the database

In order to save the values to the database, we’ll need to use the WordPress hook add_function.

The simple function we’ll use to handle the hook call back will be the following:

function update_post_recipe($post_id) {
 
 if(isset($_POST["recipe_time_in_seconds"])) {
 $meta_value = $_POST['recipe_time_in_seconds'];
 $post_meta = update_post_meta( $post_id, 'recipe_time_in_seconds', $meta_value);
 
 
 }
}

Special attention the the dark line, where we save the values into database.

update_post_meta( $post_id, ‘recipe_time_in_seconds’, $meta_value);

The parameters we sent inside the function were:

  • $post_id -> The POST ID
  • recipe_time_in_seconds’ -> The name of the field we are saving
  • $meta_value -> The value to assign to the field

More details on the update_post_meta function on the WordPress official documentation.

Once the callback function is defined, we can attach it to a WordPress event, on this case ‘save_post’.

add_action(“save_post”,”update_post_recipe”);

On this moment value is being saves on the database, inside the table wp_postmeta.

How to read this value ?

WordPress has a function to get this value from the database get_post_meta , you can use this function on your logical code or simply by showing the values on the template.

get_post_meta($post_ID, ‘recipe_time_in_seconds’, true);

By invoking this function we’ll get the value of the meta ‘recipe_time_in_seconds’ defined for the post with id $post_ID.

Calling this function on your custom template, would be as simple as:

<?php echo get_post_meta(get_the_ID(), ‘recipe_time_in_seconds’, true); ?>

Hope it helps, any question feel free to comment.

Published inRandom Thoughts

Be First to Comment

Leave a Reply

Your email address will not be published. Required fields are marked *