Shortcodes, output buffering, and WordPress functions

I have a couple of long forms which I want to output as shortcodes. Shortcode API indicates that

If the shortcode produces a lot of HTML then ob_start can be used to
capture output and convert it to a string

Read More

This seems to be exactly my case. Also, I want to use WordPress functions inside my HTML, like this:

function my_shortcode_register_form( $atts, $content = null ) {

    ob_start();
    ?>
    <div id="reg_form">
        <h2><?php echo __('Login info', 'my-plugin-domain'); ?></h2>
        <!-- and so on -->

    </div>
    <p><a href="<?php echo site_url( 'dashboard' ); ?>"><?php echo __('Go to Dashboard', 'my-plugin-domain'); ?></a>!</p>
    <?php
    $output_string = ob_get_contents();
    ob_end_clean();

    return $output_string;
}

add_shortcode('register_form', array( $this, 'my_shortcode_register_form' ));

It works fine, but I’m interested in best-practices, potential bugs, as well as performance. Any downsides to this approach? Anything that could go awfully wrong?

I saw at least one question on here warning not only use output buffering unless absolutely necessary. Should I just bring these forms out into templates instead?

Related posts

Leave a Reply

1 comment

  1. Should I just bring these forms out into templates instead?

    It depends on the form, and you haven’t printed much detail about what your forms do. Shortcodes are nice but are not the right tool for every job.

    I would:

    1. Prefer a dedicated template to a shortcode, especially for long forms. You start to get into having to handled $_POST or $_GET data in the shortcode or check for the presence of that data in your header, or other such, and that gets messy. Plus the shortcode is overhead that may be avoidable.
    2. Consider an exception to Rule #1 and make a shortcode, if the form has to be reused on multiple pages, or if such reuse is at least a plausible possibility. Honestly, if it fails the “reuse” test I don’t see the point of the shortcode at all.
    3. Consider an exception to Rule #1 and #2 if you need editable content around the shortcode.
    4. If you are writing a plugin, a shortcode is one of your better choices. You could instruct people to create a page template and insert some code, or alter rewrite rules to make your own pseudo-page but the first is off-putting for most users and the second is complex. Even asking people to paste a shortcode into the post body can cause a panic, but at some point humanity has to learn to use computers.

    I am sure there are other concerns but those are the ones that stand out to me.