Shortcode Attributes and Filters

Shortcode Attributes and Filters

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”.

Old Shortcode Generator
Old Shortcode Generator
New Attributes Filtering Options
New Attributes Filtering Options

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!!

Share on facebook
Share on twitter
Share on linkedin
Share on reddit
Share on whatsapp
Share on email
Rami Yushuvaev

Rami Yushuvaev

I'm an entrepreneur, a web developer and a blogger. I’ve contributed code to each and every release since WordPress 2.8. I'm the Hebrew GTE responsible for the translation and the release of WordPress Hebrew version. The founder and several other WordPress related projects. I work mainly with Israeli startups and hi-tech companies, providing development services.


Leave a Reply

Subscribe to our Blog

Receive email notifications when new blog posts are published.