How do I get the attributes of a short code from a post?

Your solution has helped me find an answer to my own problem of getting the attribute of a certain shortcode, but I fear there may be an issue with your approach.

You’re using preg_match to check the post_content, which will only return 1 match. If you have a post that has multiple shortcodes in it, it will only return the first one, which may not be the one you’re looking for.

Instead, you should use preg_match_all, then loop through the regex_matches array to check for the shortcode you need.

Also, you don’t need to use str_replace to remove the quotes from the string. WordPress has a built-in function shortcode_parse_atts which takes that a string of parameters (in your case it would be $regex_matches[3]) as an argument and outputs an array. This would also spare you the use of wp_parse_args function.

Leave a Comment