Capture functions that echo values in a variable

In an attempt to make theme templates modular, I removed the loop from the index.php, category.php, home.php, single.php, and page.php files. Everything worked fairly smoothly until I noticed calls to retrieve custom fields were not working.

I was using the variable $post->ID to retrieve the ID number of the current post, unfortunately, now that my loop is in an included file, this no longer functions. I had to seek another way to retrieve the value.

After searching the WordPress Codex, I didn’t find a good solution, but I did find the function the_ID() that basically echos the ID of the current post. Unfortunately, I need the value in a variable.

The solution is to use output buffering. Here’s a quick example below that’s used right here on WordPressABCD:

1
2
3
4
5
6
7
8
9
10
11
//turn on output buffering
ob_start();
 
//next the function
the_ID();
 
//copy the contents of the buffer to a variable
$post_ID = ob_get_contents();
 
//end and clean up the buffer
ob_end_clean();

This worked great for me. Hope it works for you too.

Posted on March 11th, 2009 in Tips and Tricks | No Comments