A little while ago, while working on a site built by another developer, I came across this rather interesting example of how to use custom fields badly in a WordPress theme (abbreviated for, well, brevity):

(The original also did this for meta keywords and meta descriptions — but the demonstration of this “logic” only requires one field.)



	Handwritten title

	<?= get_post_meta(334, 'meta_title', TRUE); ?> | <? bloginfo('name'); ?>

	<?= get_post_meta(383, 'meta_title', TRUE); ?> | <? bloginfo('name'); ?>

	<?= get_post_meta(381, 'meta_title', TRUE); ?> | <? bloginfo('name'); ?>

	<?= get_post_meta(383, 'meta_title', TRUE); ?> | <? bloginfo('name'); ?>

	<?= get_post_meta(387, 'meta_title', TRUE); ?> | <? bloginfo('name'); ?>


And so on. For approximately 40 separate pages. It made my brain hurt. For reference, the exact same thing — for all pages on the site — could have been accomplished (with better fallback conditions, in fact) with this code:


post->ID, 'meta_title', true)=="" && is_page() ) { ?>
	<? wp_title('|', true, 'right'); ?> <? bloginfo('name'); ?>

	<?php echo stripslashes(get_post_meta($wp_query->post->ID, 'meta_title', true)); ?> | <? bloginfo('name'); ?>


Now, the original code may actually look cleaner — it does, after all, have fewer functions and fewer variables. However, the second example is a hell of a lot more maintainable.

If you add a new page to the site in the first example, you have to:

  1. Create the new page.
  2. Add a custom field with the title.
  3. Check the new page’s ID.
  4. Find the theme file which contains the meta data references.
  5. Add a new line in the elseif loops which references your new page first by slug and then by ID

With the second example, you simply:

  1. Create the new page.
  2. Add a custom field with the title.

No coding, no PHP (Hypertext PreProcessing), no editing themes — it just works. Well, isn’t that handy? This is just basic good coding practice: make your code reusable. There’s absolutely no reason to code something into your WordPress Themes which is not readily transportable unless you’re doing yourself a favor by avoiding an unnecessary server call by hard-coding the site name or other known elements.

The basic difference between these two examples is simple: the first requires you to hard code the ID and page slug for each example; the second grabs the post ID from the existing post object. The second example also has a fall-back if no information has been entered in a given custom field — which is lacking in the original code.

Word to the wise: save yourself some work!