Getting attribute value from shortcode

I have this shortcode

  [learn_more caption="something here:"]
  [/learn_more]

I want to extract the caption value and remove other stuff. “something here:”

Read More

This is the code that I have, but it print the shortcode as it is.

 $exclude_codes = 'learn_more';
 $wp_content = preg_replace("~(?:[/?)(?!(?:$exclude_codes))[^/]]+/?]~s", '', $wp_content); 

Thanks

Related posts

Leave a Reply

2 comments

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

  2. Thanks every one for help, actually I solved the problem without using regex at all. I use wp-mpdf plugin with wp-event-manager, when I try to output the event page to PDF some content didn’t show like title, and some content, .. and that’s what cause the problem, but after some customization I was able to get the content from different places and the problem is solved.

    code from wp-mdf.php in mpdf_output function

    $EM_Event = em_get_event($post->ID, 'post_id');
    
    $wp_content = '';
    $header_content = '<h1></h1>';
    $footer_content = '';
    
    $header_content .= '<h2><a href="' . get_permalink() . '" rel="bookmark" title="Permanent Link to ' . the_title('','', false) . '">' . the_title('','', false) . '</a></h2>';
    $header_content .= '<h3>'.$EM_Event->output('#_EVENTDATES').'</h3>';            
    $header_content .= '<h3>' .$EM_Event->output('#_LOCATIONNAME') . ' - ' .$EM_Event->output('#_LOCATIONCOUNTRY'). '</h3>';
    
    $footer_content .= '<div id="footer">'; 
    $footer_content .= '<strong></strong>';
    $footer_content .= "<div>";
    
    $wp_content .= $header_content;
    $wp_content .= apply_filters('the_content', $wp_content);
    $wp_content .= $footer_content;