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
Latest posts by RafaÅ Gicgier (see all)
- WP Doin Recognized among Top Web Developers in Poland - 29 October 2019
- WordPress application development ACF & Gravity Forms - 3 August 2019
- OptiPic.io – How and why to optimize the image on the site? - 8 April 2019