Using Conditional Custom Fields for Advanced Layouts

An often overlooked function in the WordPress arsenal is Custom Fields. Overlooked because to most it makes no sense: What do you use a custom field for? And how do you use it? The answers to these questions differ depending on how the WordPress theme has been set up: Custom fields can be used for everything from passing information to plug-ins like Next Gen Gallery to feeding custom areas in the template with information. But it goes way beyond that. Custom Fields can also be used to create advanced layouts and design variances that can be triggered on a page by page or post by post basis. And this tehcnique can be edhanced further by adding conditions to the scripts so that the changes only appear when the field is actually activated.

Understanding custom fields

You can add custom fields to any WordPress post or page through the custom fields interface found right underneath the main text area. The custom field contains two elements; a name and a value. These are pretty self explanatory: When the template asks the server for the name, the value is returned. But this also means that unless the template actually asks for the field by name, nothing is returned. An example to show how this works in real life:

Artist menuA web site for an art gallery requires each artist page to have a series of sub-pages containing an artists statement, bio, CV and image gallery. Although adding an unordered list directly to the text body of the page would work, it would require the addition of style elements and tags – something WordPress doesn’t like very much. Not to mention it’s also cumbersome and messy. A better solution is to place all the style tags in the template and then just feed the menu in the form of a standard unordered list from a custom field, in this case with the name “artistMenu”. Then all that’s left is to get the template to call for the info in the custom field like this:

<div id="artistMenu">
	<?php echo get_post_meta($post->ID, "artistMenu", true); ?>		
</div>

When the template is opened, the content of the custom field named “artistMenu” is placed as a string inside the artistMenu div. (To understand exactly how the php code works you can read about the get_post_meta template tag in the WordPress Codex.)

Making the custom fields conditional

The problem with the example above is that even if there is no custom field defined, the div is still placed in the page taking up space. Not a big problem when it’s just a horizontal menu but if you use a custom field to populate something larger, like an image gallery or a text box, it will look weird if the box is left empty. One way of avoiding this is to make two separate templates, one with the custom field code and one without, but that can quickly become complicated. And the whole idea here is to make things simpler, not more complicated. A better way is to make the code and the call for the custom field conditional on whether the custom field has been defined in the first place. This can be done with a simple if statement:

<?php  if((get_post_meta($post->ID, "artistMenu", true))) { ?>
	<div id="artistMenu">
		<?php echo get_post_meta($post->ID, "artistMenu", true); ?>		
	</div>
<?php } ?>

Using conditional custom fields as design elements

Now for the really cool stuff: Because we can make custom fields conditional, and because we can populate them with pretty much anything, we can use them not only to add images or text but also to add all new design and layout elements. In the site I built for Sablok & Salbok Notaries Public I used this technique to create a header element that only appears if the custom field is populated by an image or text. The actual appearance of the element is controlled by standard CSS. You can see this layout element as the blue horizontal area in the image and on the front page of the site.

Sablok & Sablok custom fieldIn this particular example the custom field can be populated by an image. Rather than forcing the user to input all the image code in the custom field manually I added some extra code in the template that gathers the width and height of the image and creates the proper element code. As a result all the user has to do is provide the URL for the image. There is also an or condition in the if statement so that the custom field code in the template is triggered either when an image field or a text field is defined:

<?php  if((get_post_meta($post->ID, "image", true)) || (get_post_meta($post->ID, "text", true))) { ?>
	<div id="subheader">
 
		<?php if(get_post_meta($post->ID, "image", true)) {
		$size = getimagesize(get_post_meta($post->ID, "image", true)); ?>
		<img src="<?php echo get_post_meta($post->ID, "image", true); ?>" alt="" width="<?php echo $size[0]; ?>" height="<?php echo $size[1]; ?>" />
		<?php } ?>
 
		<?php if(get_post_meta($post->ID, "text", true)) {?>
		<?php echo get_post_meta($post->ID, "text", true); ?>
		<?php } ?>
 
	</div> <!-- END SUBHEADER -->
<?php } ?>
Morten Rand-Hendriksen is a web designer, developer and educator specializing in WordPress and Expression Web. He has published three books and two video series on web design with more coming, he runs a boutique style digital media company called Pink & Yellow Media and he spends a lot of his time thinking about and sharing his knowledge of the internet, information philosophy and web design and development.
Recent Related Posts
  • http://ecopupdogclothing.blogspot.com Su

    Great informative article, thanks!

    Netchick sent me :)

  • http://joax.nl Joax.nl

    i love using custom fields :D for two of my recent clients i used it to give each page a different header (if available) http://ballonbelevenis.nl & http://mentorion.nl
    since i’m only a designer it feels like a great accomplishment :P

    Greetings from the Netherlands & thanks for your blogposts

  • http://www.pinkandyellow.com Morten Rand-Hendriksen

    I know what you mean. When you realize how much you can do with custom fields it’s a bit of a “wow” moment. Nice sites btw.

  • http://www.wordcampwhistler.com/2009/01/live-notes-for-wordcamp-whistler-2009/ Live notes for WordCamp Whistler 2009 | WordCamp Whistler

    [...] Rand-Hendriksen: Using Conditional Custom Fields for Advanced Layouts 5 Comments Comments [...]

  • http://www.cssgalleries.com/2009/01/articles-and-tutorials-for-web-developers/ Articles and tutorials for web developers | CssGalleries

    [...] Using Conditional Custom Fields for Advanced Layouts [...]

  • http://www.healinggraphics.net Cathy Tibbles

    Thanks for posting the conditional code for this! Perfect… :)

    I’m using this to make some pages that look more like web pages for a client. Will be great!

    Cathy Tibbles
    @multimom

  • http://ater.com.br/2009/03/05/artigos-e-tutoriais-para-desenvolvedores-web/ Artigos e tutoriais para desenvolvedores web | Ater Internet: Empresa de webdesign

    [...] Usando Condicionais Campos Personalizados avançada para Layouts [...]

  • http://www.cssenvy.com asker

    Hello webmaster I like your post…

  • http://www.101free-stuff.com Free Stuff

    Keep working ,great job!

  • http://bazuzu.ru Nitutirlorer

    ????? ?? ????, ??????? ? ?????????

  • http://noai.ru/ borya874

    ????, ??????? ?????? ??????? ??? ???? ????? ??????????!

  • http://1ai.org/ DitobiVe

    ??? ????? ??? ??????? ?????? ? ?????? ???? ???? ? ?????????? ????????. ????? ??????? ??? ??????? ?????????.

  • http://inai.ru/ sasha854

    ?? ???? ????, ??? ????, ??? ????, ??? ???? ?_0 ??????? ??*

  • http://spworld.ru fauksiles

    ??????????, ??????? ?? ?????? ;)

  • http://pravp.ru/ HobLiece

    ??????????? ?? ????? ????? ???? ??????, ? ????????? ??? ???????-?? ???????? ?????? ?? ???. ?? ??? ????? ?????????? ???????? ?? ???????, ? ??? ???…

  • Megan

    I read your website every week, its great and got lots of information to take in and lots of interesting articles.

  • http://redheaddesign.net Jen

    Thanks! You answered a question I’ve had all day!

  • http://www.designisphilosophy.com Morten Rand-Hendriksen

    Glad I could be of help.

  • http://boinc.berkeley.edu/wiki/User_talk:Viagra_online_without_prescription Jessica

    It was really nice posting and very informative.

  • http://www.resify.com John

    Excellent! Thanks

  • http://www.webmatters.co.nz Michelle

    Thanks so much for sharing. I was using a custom field with out a conditional tag and discovered IE 8 showed a red x for the image if one was not set. All gone now!

  • http://jimba.com.np Jimba

    thanks, its really nice.
    One more question,
    if I want to duplicate the same custom field then what should I need to do?

    like:
    ID, “artistMenu”, true))) { ?>

    ID, “artistMenu”, true); ?>

    I want to show the same condition twice but off course the content will be different even the custom field name is same.

  • Alex

    THANKS!!!!

  • http://www.abbotsfordguide.ca Abbotsford Guide

    Thanks for the clarification on custom fields. I’m looking for a way to display restaurant menus, and I think this is the way to do it. Cheers.

  • http://www.photospherix.com PhotoSpherix

    Thanks man, that helped

  • http://www.eightyonedesign.co.uk/7-essential-wordpress-resources-hacks-and-plugins/ 7 essential Wordpress resources, hacks and plugins / eightyone design / graphic design blog

    [...] Custom fields are a very intuitive way of creating advanced layouts within WordPress themes. However, custom fields are often overlooked due to people not understanding what they are and how you can use them. Lucky for us then that the pink and yellow blog have written this extremely good article explaining what custom fields are. [...]

  • http://www.pstfilescan.com PST Repair

    Great site… it’s one of the easiest to follow

  • Anonymous

    Really useful site. Thank you.

  • http://abubakar.me AbuBakar

    Thanks a lot, Exactly what I was looking for. I wanted to toggle between a slide show and a static image based on existence of a custom field.

  • http://www.web-designs-company.com web design company

    Thats really very informative and useful.U have made the best points on conditional fields.

  • Dhexter_69

    You’re the best man!

  • hamilel1

    I know its a been awhile … but I’m trying to do the same thing you described: use custom fields to call a different header template for different pages but I can’t find any good instructions! Any chance you could described how you did this? Thanks.

  • http://www.webhostings.in/ web hosting in india

    Valuable information and excellent design you got here! I would like to thank you for sharing your thoughts into the stuff you post!! Thumbs up!