Home » How to get shortcode attributes from WordPress content with regex

How to get shortcode attributes from WordPress content with regex

A few different people in the WordPress support channel on IRC have asked me for how to get shortcode attributes from WordPress content. This means that they are trying to take the raw content (before it’s WordPress natively processes the content for shortcodes) and pull attributes from those shortcodes.

This has proven to be a bit tricky for plain ol’ regex because some shortcodes are self-closing shortcodes and some have a closing shortcode tag. I’m not planning on reworking this code to work for everyone all the time, so please understand that the following snippet is just a specific use-case for processing the url attribute from soundcloud shortcodes.

This will use some regex to grab all shortcodes from the content (from the $content variable in this example) and filter out the results of the url attribute for those shortcodes. Since this is just an example, I’m not even checking to see if the matched shortcode is a soundcloud shortcode but that could be done pretty easily. Use the following as a starting point for your super-hacky less-than-clean shortcode regex attribute processing needs.

It’s also good to note that there’s a global you can use for listing all active shortcodes. Here is an example of that in case you need to print them out for debugging:

Let me know if you have any questions, comments, or concerns… but again… this is just an example so please don’t expect this to work for your specific needs without changing the code a bit.

Leave a Reply

Your email address will not be published. Required fields are marked *