WordPress Coding: get_the_content() with formatting

WordPress Coding: get_the_content() with formatting

We can customize your wordpress site to meet your needs.If you have used the WordPress function get_the_content() in your theme, you have surely run into the issue of lost formatting in the output.  Normally you would use the_content() to display content but the problem with this function is it outputs immediately making it less than ideal if you want to do something with the data before you output.

Below is a simple function that allows the best of both worlds: the flexibility of get_the_content() (where you control when the output happens) with the option to perserve the formatting like the_content();

The function (place within your functions.php theme file):

function get_content_with_formatting($content){
$content = apply_filters(‘the_content’, $content);
$content = str_replace(‘]]>’, ‘]]>’, $content);
return $content;

Usage example (use within The Loop) :


// in your functions.php
function custom_loop(){
// customize the loop
$params = array(‘post_type’ => ‘post’,’posts_per_page’ => 5);

// setup the custom loop using WP_Query
$new_query = new WP_Query($params);
// the custom loop
if($new_query->have_posts()): while ($new_query->have_posts()) : $new_query->the_post();$id = get_the_ID();
$content = get_the_content();
$content_formatted = get_content_with_formatting($content);

} ?>

<?php // place below code in an output template file such as home.php to display the post content
echo custom_loop(); ?>

To see the original forum answer this post is based on go here (props to jonradio for the answer).

If you have any questions about how to use this function in your own wordpress theme or just questions in general, post them below in the comments.  Feel free to use this function in your own WordPress theme.

Thank you for reading and have a great day.

Get Started