Today we will learn how to automatically add meta boxes to custom post types in WordPress.
Without modifications, the
add_meta_box function only adds your meta box to the post type that you have specified. I will give you the code today that will allow you to add them dynamically to any new custom post types that your create. I will also show you the code so that you can skip specific post types if you so desire. Let’s get started!
Setting Up the Function
I am going to be assuming you are using WordPress 3.0 or greater. If you are not, you need to update today! 🙂 I’m not going to go through the data validation process (or input fields) for meta boxes, just the setup that displays the meta box. Here is what a typical setup for this will look like. Place the following code in your theme’s
This is your basic meta box setup. Putting this into your
functions.php file will display a meta box for the ‘post’ post type up under the Visual Editor with nothing in it (it may contain a warning, but that isn’t relevant for this tutorial). The limitation to this is that it only adds a meta box to the ‘post’ edit screen. Let’s change up the function
tgm_custom_meta_box so that it will automatically add the meta box to each new post type we create, including the default post types of post and page.
$post_types variable uses the
get_post_types function to grab all of our post types. Then we simply use a foreach statement to apply this code to each meta box. Viola! This bit of code now automatically adds meta boxes to any new custom post types that you create. Pretty nifty, right?
Even More Uses
This is pretty cool, but what if you want to specify some post types for the meta boxes not to show up? We can easily do that too. Take a look at the following modification to our function:
This is a more customized version of this function. First of all, our
$post_types variable now has a condition. The
$post_types variable will only accept post types that have the public argument set to true. There is a whole slew of arguments you could pass here. Just refer to the Codex on custom post types to learn about all the ones you could use.
Now check out the new “if” statement within the foreach construct. This “if” statement checks to see if the post type is either ‘page’ or ‘post’. If any of the “if” arguments are true, then we use continue statement to pass over that post type and go to the next post type (if there are any left in the array). You can add or take away from this as you would like to customize where your meta boxes are displayed.
And that just about wraps it up! I hope you’ve enjoyed the tutorial on how to automatically add meta boxes to custom post types. Be sure to tell all your friends! 🙂