Shortcodes in text widgets
Shortcode in WordPress gives both programmers and users flexibilities. Combining shortcodes and widgets, coders can have less code in their theme, plugin. Calling shortcodes with different parameters helps users using code easier.
However, there are some issues that I have seen many people facing to.
1. Shortcodes by default do not run in text widgets.
A text widget is… a text widget 🙂 It is showing text, not processing PHP code by default. For allowing shortcodes working with text widgets, add this function to your functions.php file.
2. Echo vs. return.
Another issue when displaying results with shortcodes and widgets. If you are using “echo” directly, you will notice that the HTML output will be displayed outside of the widget wrapper. It is because the PHP code is processed directly before the widget is completed. The correct command should be “return”. The PHP code is still processed but not displaying immediately. The output will be saved in one value, and it will be code inside the widget loop.
The WordPress codex is also giving a warning about this issue:
Shortcode functions should return the text that is to be used to replace the shortcode. Producing the output directly will lead to unexpected results.
So, for using shortcodes with text widgets, you will need to remember two things:
- Allowing shortcodes running in text widgets by adding above function into your functions.php file.
- And using “return” instead of “echo” for showing the HTML output.