Thursday, September 8, 2016

Quick Tip: How to Use Shortcodes Within Widgets in WordPress

We can do a lot of different things with shortcodes in WordPress, as we explored in our article describing the WordPress Shortcode API. However, by default, WordPress only allows the use of shortcodes in posts (and pages), and not anywhere else.

If you want to use shortcodes in widgets, it’s not possible by default. However, in this quick tip, I'll cover how you can enable this functionality.

no shortcode in widget

Allowing the Use of Shortcodes in the Text Widget

WordPress provides several widgets by default. One of them is the 'Text' widget, which, as its name suggests, allows you to add any text to a widget. You can also use it to add any HTML code.

That means that you can also play with JavaScript code in this widget, so it's pretty powerful. However, if you need more, like a PHP script to access some data stored in the server, this widget won’t help you by default.

It’s similar to a post. That’s why, like in a post, we would like to be able to use shortcodes to do anything we want. To do that, we can use the widget_text filter. This filter is called to allow modifications in the content of a 'Text' widget. We'll use it here to ask WordPress to parse shortcodes in this widget.

Parsing shortcodes in WordPress is achieved thanks to the do_shortcode() function. It accepts one required parameter, the text to parse, and it returns the parsed text. That means that we can directly use this function as a callback function in the widget_text filter.

Continue reading %Quick Tip: How to Use Shortcodes Within Widgets in WordPress%


by Jérémy Heleine via SitePoint

No comments:

Post a Comment