Exciting new stuff here at GWP! We finished rewriting the Shortcode Generator, removing the extract()
function and supporting the optional shortcode_atts_{$shortcode}
filter in your shortcode.
The extract() function
extract() is a PHP function, it receives an associative array. For each key/value pair it will create a variable. This function treats each keys as a variable-names and each values as a variable-values.
Some developers love to use extract()
because it make the development easy, but others argue that it makes the code harder to understand and harder to debug. The WordPress core team discourage developers using this function and they removed it from the core entirely.
Shortcode Generator Attributes
We have transformed our Shortcode Generator removing the extract()
function from the code.
This change affect your old snippets. If your shortcode has an id
attribute, with extract()
you retrieved the attribute value using $id
variable, but now without extract()
you need to use $atts['id']
. Please update your snippets.
Retrieve attributes the old way:
Retrieve attributes the new way:
Filtering Shortcode Attributes
While working on the shortcode generator we added an extra bonus – the ability to leverage the hooks mechanism to make your attributes filterable. Now you can add shortcode_atts_{$shortcode}
filter to your shortcode with a few clicks of a button.
Since WordPress 3.6, we can add shortcode attributes filter. But it’s up to the developer whether to support this kind of filter. It’s done using the shortcode_atts()
function’s third parameter. By default, your shortcode won’t have this filter. To add this filter, the developer need to supply the filter name. It’s recommended to use the shortcode tag-name as the filter-name, but you can choose any other name.
We added two more fields to the shortcode generator to support this nifty feature – “Add Attributes Filter” and “Custom Filter Name”.
In the shortcode generator, you can select not to support the attributes filter (default behavior), to support the filter using the tag-name (recommended), or to support the filter using a custom-name you choose.
Enjoy coding!!
5 Comments:
mcar2n
Thank you. that was helpful.
linkpakdigital
You’re genius. Thank you, it saved my plenty of time.
Linkpak Digital
Very helpful. Where I can find function shortcode_atts()?
Rami Yushuvaev
For more information about `shortcode_atts()` function, check the official code reference:
https://developer.wordpress.org/reference/functions/shortcode_atts/