Getting attribute value from shortcode

I read your question differently than @eric-holmes. It sounds to me like your shortcode needs to function normally under most circumstances but that you are extracting information in special circumstances.

Shortcode regex is tricky. Let WordPress do it for you.

$pattern = get_shortcode_regex();
preg_match_all("/$pattern/",$wp_content,$matches);

Your attributes for any shortcodes present in $wp_content should now be in $matches[3]. You want to do something like…

$lm_shortcode = array_keys($matches[2],'learn_more');
if (!empty($lm_shortcode)) {
    foreach($lm_shortcode as $sc) {
      $captions[] = $matches[3][$sc];
    }
}

You will still need to clean the string a little bit as you will have a “caption=” in there but you are far ahead of where you started, and you could do that at the same time you set $captions with str_replace or preg_replace depending on how complicated you need the match.

Getting attribute value from shortcode

Leave a Comment