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
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?
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:
$_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.I am sure there are other concerns but those are the ones that stand out to me.