1

I'm trying to display a texts with functions on my page. Please find the code below. I'm not getting the output I want.

<?php $content = the_content(); ?>
<?php printf(__('Output : %1$s', 'theme'), $content); ?>

Which Outputs :

Foo
Output  :

I need my output to be like this :

Output  : Foo

Answer from Kim Christensen :

<?php $content = get_the_content(); ?>
<?php printf(__('Output : %1$s', 'theme'), $content); ?>

Works perfectly :

Output : Foo

Answer from Pieter Goosen :

<?php $content = apply_filters( 'the_content', get_the_content() ); ?>
<?php printf(__('Output : %1$s', 'theme'), $content); ?>

It pushes my content below :

Output :
Foo

4 Answers 4

1

the_content() prints it output to screen. What you want is to return that output and assign a variable to it.

You should note, although get_the_content() do exactly what you want, it only returns unfiltered content, and not filtered content like the_content(). You should manually add those filters, which is real easy.

You can do the following

$content = apply_filters( 'the_content', get_the_content() );

EDIT

It seems the above approach pushes the content part to the next line when the filters are applied to get_the_content().

A work around here would be to concatenate Output : to get_the_content() and then applying the content filters to that

<?php $content = apply_filters( 'the_content', 'Output :' . get_the_content() ); ?>
<?php printf(__( '%1$s', 'theme'), $content); ?>

would give you what you need

7
  • Hi Pieter, I've tried your code. However, it pushes my content below. Please check my edits above. Thanks.
    – KC Chai
    Apr 29, 2015 at 5:48
  • Don't you have a line break right at the top of your content Apr 29, 2015 at 5:53
  • Looking at your last update, it seems that when the filters is applied on get_the_content(), the issue starts which can be because of the added p tags or a line break Apr 29, 2015 at 6:01
  • Thanks Pieter, I thought it follows the printf? Is there a way to ignore the line break?
    – KC Chai
    Apr 29, 2015 at 6:01
  • Please see my update, it should work now Apr 29, 2015 at 18:51
2

You want to use get_the_content(), the_content() prints the content.

get_the_content() will be assigned to your variable.

1

Kim is correct.

get_the_content() displays your intended result.

<?php $content = get_the_content(); 
printf("Output: %1$s", $content); ?>
-1

Another approach:

ob_start();
the_content();
$content = ob_get_clean();

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.