0

I am building a word press plugin and I need to get back the page and post content as an html string. I want it back as a string so that I can search the DOM for particular elements with a tag and then do something with those elements when found.

The problem is when I use

the_content();

or

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

It seems to always display (render) the content on my plugin page which is not what I want. I just want the output back as a string.

AdaRaider
  • 1,126
  • 9
  • 20

1 Answers1

2

This is wrong

$the_content()

To be honest I am not sure how that works with a $, but any call to the_content() will just output it.

You can use

get_the_content( string $more_link_text = null, bool $strip_teaser = false )

Retrieve the post content [as a string]

In any case you can always use output buffering, if no other way exists

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

you can see this answer about what Output buffering is.

What is output buffering?

Basically when you output "stuff" it goes into a buffer, normally you have no control over this and it eventually gets dumped into the response. With output buffering you can capture that "stuff" into a buffer you can control.

Obviously it's preferable to use a method that returns a string directly, I just thought I would share the Output buffering "method" in case you need that ability for something that does not provide such a method.

Cheers!

Community
  • 1
  • 1
ArtisticPhoenix
  • 21,464
  • 2
  • 24
  • 38
  • Thank you, I am quite new to both word press and php you seemed to understand what I was asking anyway, cheers! – AdaRaider Apr 12 '19 at 04:07
  • 1
    I been doing PHP for over a decade and I manage around 6 wordpress sites for our company ... lol ... That said they don't let me do much design work anymore. My PHP skillz are too valuable... For example I just created a Rest API over the last 2 weeks, using RabbitMq and Sphinx search engine... :-) I'm actually taking a break from documenting it. (yes it's after hours... I have many projects to do) – ArtisticPhoenix Apr 12 '19 at 04:07