Custom Meta Box (Harder)

Same task as the previous post, but without using a plugin this time. I found an excellent tutorial at DeluxeBlogTips.com. It provides full sample code and explanation. The WordPress codex has sample code too, but it wasn’t clearly explained there.

To keep things neat and easy to modify, the code here used an array to store the parameters so the function call can be kept the same.

There are three parts to adding a meta box. The first is to add the box. This is done with the add_meta_box() WordPress function. The parameters are explained at the codex page.

The second step is to define the callback function which prints the HTML shown in the meta box. The tutorial uses a foreach loop to go through all the fields and a switch statement to print the output, depending on what the type of control it is.

The final step is to save the data. Some checks on whether the request is valid and whether the user is allowed to edit the page must be done. This is done in a separate function.

Remember that these functions must then be hooked onto WordPress with the add_action() function.

add_action('admin_menu', 'add_box');
add_action('save_post', 'save_data');

One action for adding the box to the interface, and the other for saving the data. Hook them to the admin_menu and save_post hooks.

About these ads

2 thoughts on “Custom Meta Box (Harder)”

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s