When creating a metabox do you have to create DB fields for the data?

When adding a metabox, the metabox itself isn’t saved in the database. It’s loaded from the plugin code that is written, then it’s up to you to fill it with appropriate values.

You don’t have to create additional fields in the DB. There is a function:

update_post_meta($post_id, $meta_key, $meta_value);

In your case you might do something like:

update_post_meta($postId, "my_custom_metabox_title", $titleValue);
update_post_meta($postId, "my_custom_metabox_desc", $desc);
update_post_meta($postId, "my_custom_metabox_forsale", $forSale);

This would update (or add if not already there) data in the table wp_postmeta which has the following columns:

  • meta_id – table’s primary key
  • post_id – the post id
  • meta_key – whichever key you pass in the second argument (ex: “my_custom_metabox_title”)
  • meta_value – whichever value you pass in the third argument of above function. If the value is an array or object, it will save the data as a serialized string

Once the data is in the DB, you could then use another function to get the data:

$customTitle = get_post_meta($postId, "my_custom_metabox_title", true);
$customDesc = get_post_meta($postId, "my_custom_metabox_desc", true);
$forSale = get_post_meta($postId, "my_custom_metabox_forsale", true);

The function accepts the following:

  • postId – postId of the post
  • metaKey(optional) – key of the metadata you want to retrieve – if left out, it will return all metadata in an associative array (the array key would map to the meta_key)
  • single (boolean optional) – if set to true, it will return the first object/string based on the key. If it was serialized data, the returned object will be unserialzed. If set to false, it will return the result as an array. If only one result, the result will be in $result[0]