Assume I have a function that returns HTML output after it's done processing it:

function parse_html_for_images() {
    return '<img src="' . thumbnail_url() . '">';

I need to output this string, say, for the thumbnail of a post on a custom built page.

My mind goes to echo parse_html_for_images() but this feels somewhat weak, hear me out:

echo to me feels like a "finish everything after this and don't output anything else".

Then I discovered ob_start which creates a buffer for me. Which is exactly what my mind thinks "alright, a place where I can hold on to a lot of data, without outputting it before it's done with everything".

But wouldn't it conflict with, say, esc_html_ and the likes?

Any guidelines?

1 Answer 1


It depends on the context. In a template you'd just echo it:

    <?php echo parse_html_for_images(); ?>

In a function you might want to concatenate it with something else:

function wpse_303376_thumbnail() {
    return '<div>' . parse_html_for_images() . '</div>';

In a shortcode callback with lots other markup you might want to use output buffering, since shortcodes require you return the entire output:

function wpse_303376_shortcode() {

    echo '<div>';
    echo parse_html_for_images();
    echo '</div>';

    return ob_get_clean();

Escaping is an entirely separate issue, and is about ensuring unsafe data, like user input, can't do anything malicious or break your markup. For example, you might want to escape the thumbnail URL in your function to ensure it's a URL and not a script tag:

function parse_html_for_images() {
    return '<img src="' . esc_url( thumbnail_url() ) . '">';

But there's no point escaping HTML that you have hard-coded into the template or function, since it's predictable.

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.