WordPress: Adding meta boxes

In an earlier post, I created some custom post types from scratch. They’re working, but they’re mostly still sitting there with their default settings. So they just have a title field and a big ol’ description field. I need to add some custom fields. The first one I’d like to add is a FAQ field. I guess that will be a question field and a corresponding answer field. And the user should be able to create as many as he or she would like (I believe that’s called a “repeatable” field). < … googling … > I found what appears to be a solid tutorial on creating metaboxes with all kinds of fields – including repeatable fields. I’m going to start here and see how it goes. Hmm … just realized … I want to create a meta box that will appear on a Page, but I don’t know where to put the code. 

Getting the meta box to appear on a Page is very simple. The add_meta_box() method has an option $page where you can specify the $post_type on which it should appear. Simply set it to “page” and you’re good to go.

< Need to detail the difficulties with creating a repeatable FAQ item meta box >

I now need to list all the FAQ items on the page. First I simply need to put the page title and content on the page. The title is straightforward:

<h1><?php the_title(); ?></h1>

But how do I get the content for a single page to appear without using The Loop?

< … some googling … >

Apparently there is no way to avoid this. Seems silly to have a whole loop set up when I know I will only ever have one title and one content item. Oh well.

Side note: I need to integrate data sanitization into my meta boxes.

Another problem I’ve run into is how do I get a meta box to appear only on a specific page in the admin interface? It turns out that there is no good way to do this. Actually the question itself doesn’t really make sense. Let’s break it down: I want the FAQ item meta box to only appear on my FAQ page. If I haven’t already created that page, how can I write any kind of conditional to include it? If I have already created the page, I can then say something like “if this is the FAQ page, include the meta box.” But then I get the awkward progression: 1) Create and save the FAQ page, 2) Reload the FAQ page so the meta box appears.

I think what I’d like to do is include a button that can add the meta box dynamically to any page. So the user can click “Add FAQ items to this page” and the meta box will appear. In that case I will have to move the loop that displays the FAQ items to a more general Page template (right now it’s only on the FAQ page. I’m not sure how to set that up.

Leave a Reply