Weekend QuickTip: Post Meta in Sidebar

3 Comments

Ever wanted to include additional data from your post’s custom fields in the sidebar of your page? Almost every theme utilizes the sidebar.php template, but if you’ve ever tried to use the standard method of calling custom field data in the sidebar, you’ll know that it doesn’t work like you’d expect it to. Here’s the workaround.

First, in either page.php or single.php, you need to add a few lines of PHP inside the loop:

<?php if(have_posts()) : while(have_posts()) : the_post(); ?>
<?php global $wp_query; $postID = $wp_query->post->ID; ?>
			
// loop stuff

<?php endwhile; endif; ?>

Notice this line in particular:

<?php global $wp_query; $postID = $wp_query->post->ID; ?>

This line assigns this particular post’s ID to the variable $postID.

Now, head over to sidebar.php and find where you want to display the custom field data. After we globalize $postID, we can continue to call custom fields as usual, using that variable for the first parameter:

<?php 
global $postID;
$key1 = get_post_meta($postID, 'image1', true); if($key1) { echo "<p>$key1</p>"; }
$key2 = get_post_meta($postID, 'image2', true); if($key2) { echo "<p>$key2</p>"; } 
?> 

If this is a bit different than how you usually do it, here’s the code expanded and explained:

<?php 
global $postID;
$key1 = get_post_meta($postID, 'image1', true); // to avoid using the 
get_post_meta function three times in a line, we assign it to the variable $key1
if($key1) { // if data exists for this custom field
echo "<p>$key1</p>"; // display the custom field's data 
(contained in the $key1 variable)
} ?> 

3 thoughts on “Weekend QuickTip: Post Meta in Sidebar

  1. Pingback: links for 2008-11-09 | links | WereWP

  2. Pingback: BlogBuzz November 15, 2008 | Webmaster-Source

  3. Thanks for the example, helped me a lot. There is an error in this code though; $postID isn’t globalized specifically and on my php engine it doesn’t work without globalizing it first. So, instead of:
    post->ID; ?>

    I got it to work with:
    post->ID; ?>

Comments are closed.