Use output control with shortcodes
WordPress shortcodes are powerful. (period)
To quote a wordpress.com entry on shortcodes:
A shortcode is a WordPress-specific code that lets you do nifty things with very little effort. Shortcodes can embed files or create objects that would normally require lots of complicated, ugly code in just one line. Shortcode = shortcut.
They give extra power to the already powerful CMS.
The above may be troublesome
There appears to be one problem with them – it’s quite a challenge to write clean looking shortcode code. This is due to the fact that all of the content generated by shortcode has to be returned, there’s no echoing.
- WordPress loops built with WP_Query
- When there’s extra HTML to be outputted while trying to avoid extensive usage of hard to read echo instruction
For example I tend to organize my code in the following way:
A question arrises? How to do it within a shortcode?
Avoid the hard to read (and debug code)
I’ve seen numerous shortcodes written more or less like that:
Why is it wrong?
- it’s hard to debug
- it’s hard to change
- it’s hard to read
- the code within the echo quotes is not coloured in IDE, which makes it even harder to debug
Output control is teh solution!
The Output Control functions allow you to control when output is sent from the script. This can be useful in several different situations, especially if you need to send headers to the browser after your script has began outputting data. The Output Control functions do not affect headers sent using header() or setcookie(), only functions such as echo and data between blocks of PHP code.
Say we need to create a shortcode that lists 5 most recent posts from a given category:
- We need to use a loop
- We want to write nicely formatted code
Now the above gist should be self explanatory.
1. We start off with
This will store any output within the buffer.
2. We process our code, rendering some data in a clean way.
3. We take the contents of the output buffer and erase it.
4. We return them.
This technique should prevent you (and the others) from having to iterate every single line of poor code :p