How to store WordPress Post Content in to a PHP variable

If you are developing something with WordPress you may need to create a variable in which to insert the content of a post. Something like:

$content = ..post content..

Classic the_content() function just prints the content of the article but does not allow to save it as a variable, unless you use content buffer. On the other hand  the content can be easily stored into a variable using get_the_content() function, even if if it does not return the content in the same way the_content() does it, since text is unformatted.

You can call get_the_content() function even outside the loop using the global variable $post:

global $post;
$content = $post->post_content;
In so doing post content will be saved within the $content variable and will then be available to you when you want to use it.

Leave a Reply

Your email address will not be published. Required fields are marked *