How to: Retreive Custom Field Data in a WordPress Post

Purpose: use WordPress’s “Custom Field” key/data pairs to store and retrieve specific post information and display it in your own custom templates.

how this works

I like to store post information in the form of key/data pairs utilizing WordPress’s “Custom Fields” for posts. You can make up any particular key/data pair you desire — I choose, in this instance, to use key/data pairs to supplement some event information in some of my posts. You can see an example of this at rosaleeshow.com.

(To implement this, you will need some familiarity with customizing a wordpress theme.)

First, I created a function that takes an array of keys as an argument; these are the key values the function will search for in the post meta data looking for custom field information. If a matching key is found, it will display that value in a definition list.

I used this function called eventmetadl():

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
<?php //first argument: current post; 
      //second argument, array of keys to search through
function eventmetadl($postID, $metaArray) { 
 
  //this array will hold the key/data if matches are found
  $metaList = array();
 
  //search through each item passed to the function 
  foreach($metaArray as $meta) {
 
    //for each key, get the data
    $metadata = get_post_meta($postID, $meta, true); 
 
    //if there is data then add that key/data to the list
    if ($metadata != NULL ) { 
      $metaList["$meta"] = $metadata; 
    }
  }
 
  //if there is a list of meta data then:
  if ($metaList != NULL) { 
    echo "<dl>"; //open the definition list, etc
 
    //go through each item and print title/defition
    foreach($metaList as $dt => $dd ) { 
      echo "<dt>" . $dt . ":</dt><dd>" . $dd . "</dd>";
    }
 
    echo "</dl>"; // close the definition list
  }
}
?>

Then, inside my sidebar.php file in my theme, I create an array of the keys I am looking for and call my function to create the definition list. If no keys are found to match, no list is created.

<?php // in my sidebar.php file - could be in any template
  $metatags = array("Location", "Ticket Price", "Contact", "Website");
  eventmetadl($post->ID, $metatags);
?>

I have used this technique with considerable success — however, I am sure I stole the idea from someone else. Thanks to that person, wherever they may be.

Comments are closed.