This post is part of the WordPress Plugin tutorial series. To find a link to all tutorials in order, then please click here.

WordPress meta boxes are used to display certain information or options in a page. It’s when you have something to display and don’t want it to have a page of its own, but would like it to be a part of a page. An example of a meta boxes is the ones you see on the WordPress admin dashboard. Let’s create a meta box.

WordPress Meta Boxes

Create a new plugin called wpMetaBoxesand open up your index.php file. Let’s update it to this.

PHP

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

<?php

/*

* Plugin Name: WP Meta Boxes

* Plugin URI: http://jaskokoyn.com

* Description: A Basic WordPress to show how meta boxes work.

* Author: Jasko Koyn

* Version: 1.0

* Author URI: http://jaskokoyn.com

*/

// Set up our WordPress Plugin

functionjk_check_WP_ver()

{

if(version_compare(get_bloginfo('version'),'3.0','<'))

{

wp_die("You must update WordPress to use this plugin!");

}

}

register_activation_hook(__FILE__,'jk_check_WP_ver');

// Include or Require any files

include('inc/func.inc.php');

// Action & Filter Hooks

add_action('add_meta_boxes','jk_mb_create');

?>

We’re hooking into the add_meta_boxesaction. This action is triggered when WordPress starts adding meta boxes to the page. We must hook into this before we actually create a meta box because we only want to create meta boxes when WordPress allows it. We also include a file called func.inc.php. This file will contain our function we called for in our action hook.

We haven’t talked about post types yet, but just know that it’s what kind of content you’re using. Post is the most common post type. It’s what you see when you are creating or editing a post. In our case, we’re adding our meta box to the post type of post. You’ll see what I mean in a second. The priority is also different from what we’re use to. Instead of numbers, it uses high, core, default and low. Before we activate our plugin, we must first create the callback function we called in our add_meta_boxfunction.

Add this function after the jk_mb_createfunction.

PHP

1

2

3

4

functionjk_mb_message()

{

echo'This is a custom metabox!';

}

Here, we’re echoing out ‘This a custom metabox!’. We can echo out anything we want. This will be displayed to our user. Let’s save our file and then activate our plugin. You should get what you see below when you try to add a new post.

WordPress Meta Boxes

Conclusion

Creating WordPress meta boxes can be very useful to your plugins. It’s best that you use meta boxes instead of creating your own because it’s consistent. Your plugins looks should match the theme of the WordPress admin dashboard as much as possible. If you would like to learn more about meta boxes, click here.