Posted under: Blog

January 17th, 2011

How to Create a Flexible Page Template Using Custom Fields

While working with my friends over at Gastronaut, they asked me if I could develop a way for them to create blog pages for each of their clients on the fly.  For instance, if they acquired ACME Corp as a client, they wanted to be able to create  a new page for ACME corp that would then have a list of blog posts that were only for ACME.

Typically I’d create a custom page template for the client, and then use the query posts function to find only posts categorized as “ACME.”  However, since their clientele are growing, I didn’t want to have to create a new page template each time they acquired new business. Besides, that’s just too many page templates!  I searched around for what other wordpress developers might have done and surprisingly I didn’t find much.

So, here’s what I did:

I made a new page template and at the top I created a variable called $clientCategory and set its value to the “client” custom field value for the page in question. In our example, the client would create a page and using a custom field on the page, they’d type in “ACME.”

<?php $clientCategory = get_post_meta($post->ID, 'client', true); ?>

So at this point in our example, the $clientCategory variable value is  ”ACME.”

Next, I use the global $query_string variable in order to find posts that aren’t just the contents of the page in WordPress.  And then I use the query_posts function to find all posts that have a category name equal to the value set in the page’s “client” custom field.  To do this, I concatenate the $clientCategory variable that we set above to the end of the category_name argument as so:

<?php
   global $query_string;
   query_posts('category_name=' . $clientCategory);
?>

So now if the client wants to create posts for ACME and have them show up on ACME’s page, all they have to do is categorize each post as ACME.  Now of course, this means that the Category Name and the “Client” custom field value on the Page have to be exactly the same in order for this to work, but it means that the client can create these pages on the fly and I don’t need to create new page templates.

For example, if they want to create a page of posts for a new client “Widgets Inc.” they simply need to create a new post category “Widgets” and then create a new page that uses the new page template, and enter in “Widgets” as the “client” custom field value for the new page.

I hope this makes sense, and I hope it helps!

By: | Comments Off

Private