WordPress is a great tool for blogging, but can also be integrated in a website to provide a simple content management system. In this post I’m going to address the issue of the WordPress functions where they print the output directly and show how to catch this output in a variable.
After integrating WordPress in your code, post content can easily be queried by using the query_posts function. Along with some extra functions and setup, in the example below we show the last 10 posts orderedy by the post title (descending) from post category 3.
// Get all posts $posts = get_posts("numberposts=10&order=DSC&orderby=post_title&cat=3"); // Output each post global $post; foreach ($posts as $post): setup_postdata($post); echo '
'; the_title(); echo ''; the_content(); endforeach;
the_content() in the above example output the content directly on the web page, so it is important to place the code exactly there where you want the content to be showed.
However, in some more dynamic environments you might want to generate your content before you actually display it on the web page. That is, one can require the content to be stored in a variable that is to be printed later on or used for further processing before displaying it.
It is not possible to simply use
$variable = the_title();
since you cannot catch an already echoed value into a variable.
To solve this problem we can use output buffering to buffer our (local) output and in that way catch our printed content. It is not necessary to understand how output buffering works exactly, so you can just look at the extended code below which demonstrates how the previously showed code example can be transformed to accomplish the desired result.
ob_start(); // Get all posts $posts = get_posts("numberposts=10&order=DSC&orderby=post_title&cat=3"); // Output each post global $post; foreach ($posts as $post): setup_postdata($post); echo '
'; the_title(); echo ''; the_content(); endforeach; $variable = ob_get_contents(); ob_end_clean();
So essentially you start your output buffering by placing
ob_start() before the actual code you want to buffer, and similarly
ob_end_clean() when you want the buffering to be finished. To save all the output data you simply use the output of
ob_get_contents() and place it in a variable. Note that you have to use
ob_get_contents() before calling
ob_end_clean() since the latter will clear the buffer.