How to use custom fields in WordPress header, sidebar, footer templates

I’ve been using a plugin called TDO Mini Forms a lot lately to make my WordPress sites interactive. This plugin lets visitors enter data which is then used to create a new entry or edit an existing one. The site I setup this way is at http://indilean.com so you can check it out if you’d like. Now I wanted to expand on my WordPress entries to allow for more variety in a post than just the title and content. This is where custom fields come in.

On a normal entry, in the body of the entry, all you have to do to display a custom field is call the PHP code something like this: <?php $test = get_post_meta($post->ID, ‘Test:’, true); if($test) : ?><?php echo $test; ?>, <?php endif; ?> where Test: is the name of the custom field. You get to make up the name of the string but in this case I just used $test. So the above code would print the value of whatever information is contained in the Test: custom field.

Now that’s all well and good on the single.php wordpress theme template (which can be found under Appearance > Editor > single.php but what if you want to display that custom field data somewhere else on your page? Like maybe in the header within a javascript for a Google map that is being displayed in the body? Or maybe in the sidebar or footer just to mix up the formatting and spread out the content for your visitor? To do this you need to use the following code to call the variables of the entry in order to then have them printed: <?php global $post; ?>

The command <?php global $post; ?> calls the global variables from the post and then allows you to work with them as described above. One other handy piece of code to use in PHP first determines if the entry is a single and won’t execute otherwise. My full code looks like this for the header.php template that creates a Google map using API 3 and several custom fields with latitude longitude information and address information that gets put into a popup. The final page is pictured below the code.

<?php /* If this is a singly entry */ if (is_single()) { ?>
<?php global $post; ?>
<script type=”text/javascript”>

(function() {
window.onload = function() {

var latlng = new google.maps.LatLng(<?php $latitude = get_post_meta($post->ID, ‘Latitude:’, true); $longitude = get_post_meta($post->ID, ‘Longitude:’, true); if(isset($latitude, $longitude)) : ?><?php echo $latitude; ?> , <?php echo $longitude; ?><?php endif; ?>);

// add options to map
var options = {
center: latlng,
zoom: 18,
mapTypeId: google.maps.MapTypeId.HYBRID,
scrollwheel: false,
streetViewControl: true,
disableDefaultUI: true,
mapTypeControl: true,
navigationControl: true,
mapTypeControlOptions: {
style: google.maps.MapTypeControlStyle.DROPDOWN_MENU
}
};

// create map
var map = new google.maps.Map(document.getElementById(‘map_canvas’), options);

// add station to map
var marker = new google.maps.Marker({
position: new google.maps.LatLng(<?php $latitude = get_post_meta($post->ID, ‘Latitude:’, true); $longitude = get_post_meta($post->ID, ‘Longitude:’, true); if(isset($latitude, $longitude)) : ?><?php echo $latitude; ?> , <?php echo $longitude; ?><?php endif; ?>),
map: map,
title: ‘<?php the_title(); ?> Electric Vehicle Charging Station’
});

// add click to infowindow
google.maps.event.addListener(marker, ‘click’, function() {
infowindow.open(map, marker);
});

// add infowindow to map
var infowindow = new google.maps.InfoWindow();
infowindow.setContent(‘<div><strong><?php the_title(); ?></strong><br /><?php $address = get_post_meta($post->ID, ‘Address:’, true); if($address) : ?><?php echo $address; ?><br /><?php endif; ?><?php $city = get_post_meta($post->ID, ‘City:’, true); if($city) : ?><?php echo $city; ?>, <?php endif; ?><?php $state = get_post_meta($post->ID, ‘State:’, true); if($state) : ?><?php echo $state; ?>, <?php endif; ?><?php $province = get_post_meta($post->ID, ‘Province:’, true); if($province) : ?><?php echo $province; ?>, <?php endif; ?><?php $zip_code = get_post_meta($post->ID, ‘Zip Code:’, true); if($zip_code) : ?><?php echo $zip_code; ?><?php endif; ?><br /><a href=”<?php the_permalink(); ?>#directions”>Get Directions</a></div>’);

};

})();

</script>
<?php } ?>

The code above is from my header.php theme file in WordPress and uses custom fields that are entered by users to identify an electric vehicle charging station. The output page is below:

4 comments

  1. Or – for a codeless approach, you could use the Graceful Sidebar Plugin that I just recently wrote and published. This plugin enables you to create custom fields in a page or post that will be displayed in the sidebar using the Graceful Sidebar Widget.

  2. Thanks alot for posting this stuff. I was seeking help to call a custom field in my slider present at header section. I will try it and get back to you if it works.

    Amit

  3. Great post it will help me a lot, but i’ve at first an other problem :
    I’ve the code to allow visitor to post an article on my wp, but i dont know how to have their name and url. I think it’s impossible, except if i use a custom field like “author_name” and “author_url”. But i dont know which code i have to add on my template to allow visitor to give these informations.
    To make a long story short : how to put custom field writable without any access to the administration for visitor ?
    ( I hope u’ll understand my english :P )
    Thx (:

    • Good question Hugo, you might have to add in Custom Fields and some extra template code to call and write those fields into your entries. I have done this at http://electric.carstations.com/add with all of the extra fields like address and charger type etc. Here’s what it looks like in form HTML view:
      <?php if(isset($post_args[“customfields-tf-9-tf”])) {
      $temp_text = $post_args[“customfields-tf-9-tf”];
      } else {
      $temp_text = “”;
      } ?>
      <label for=”customfields-tf-9-tf”>Address:</label> <input type=”text” title=”Address:” name=”customfields-tf-9-tf” id=”customfields-tf-9-tf” size=”30″ onchange=”showAddressFromFields(); return false;” value=”<?php echo htmlentities($temp_text,ENT_QUOTES,get_bloginfo(‘charset’)); ?>”/><br />
      Once you are able to collect custom field information you just have to be able to display it on a page. To do this you need to call it in and if you want it to show up in the footer or sidebar or something you need an extra bit of code like this <?php global $post; ?>
      Here is example code I use for the sidebar at CarStations to call in the custom field for charge station technology, tesla connector:
      <?php $tsla = get_post_meta($post->ID, ‘Tesla Connector’, true); if($tsla) : ?><a href=”http://www.teslamotors.com/”>~240V Level 2: Tesla Connector (Tesla Roadster)</a>: <?php echo $tsla; ?><br /><?php endif; ?>
      So I have to say, if true (like there is content for this custom field) then print this information with this link. You can also have it print something the user typed like the address example from above, this is the code from my single entry template that prints the address a user submits:
      <?php $address = get_post_meta($post->ID, ‘Address:’, true); if($address) : ?><?php echo $address; ?><br /><?php endif; ?>
      I hope this helps! Good luck.