Search code examples
phpregexwordpresspreg-replaceshortcode

Replace Wordpress shortcode containing id with html markup using the id


I'm building a filter plugin in Wordpress and I'm replacing some plugin specific tags with bits of html.

Example: [VIDEO ID=12] will be replaced via preg_replaced in this function

function display_video($text){
   
   $pattern = '/\[VIDEO ID\=\d+\]/';
   
   $text=preg_replace($pattern,get_video_block($id),$text);
   
   return $text;
}

I'm not exactly sure how to make sure I supply the correct ($id) param to my get_video_block() function for each replacement occurrence.

There's no real loop going on other than inside the preg_replace() function so, how would I supply that value?

For more context, get_video_block() function:

function get_video_block($id){
    global $wpdb;
    $wpdb->show_errors();
    $table_name = $wpdb->prefix . "video_manager";
    $query = "SELECT * FROM " . $table_name . " WHERE `index` = '$id'"; 
    $results = $wpdb->get_results($query, ARRAY_A);
    
    $results = $results[0];
    
    $returnString = '<div class="vidBlock">';
        $returnString .= $results['embed_code'];
        
        $returnString .= '<div class="voteBar">';
            $returnString .= $results['vote_text'];
            $returnString .= '<input type="button" value="YES" class="voteButton">';
            $returnString .= '<input type="button" value="NO" class="voteButton">';
        $returnString .= '</div>';
        
        $returnString .= $results['title'] . '<br>';
        $returnString .= $results['description'] . '<br>';
    
    $returnString .= '</div>';
    
    return $returnString;
    
}

Solution

  • You can use preg_replace_callback() for that purpose. You'll also need to wrap \d+ in ( parentheses ) so it can be captured and used in the callback function.

    function display_video($text) {
        $callback = create_function('$matches', 'return get_video_block($matches[1])');
        return preg_replace_callback('/\[VIDEO ID\=(\d+)\]/', $callback, $text);
    }
    

    Note that $matches[1] is used because $matches[0] contains the entire string matched by the regular expression.

    Erwin's comment may be of use to you — WordPress has a shortcode API that manages parsing of shortcodes for you, so you can concentrate on dealing with what you want to do with the shortcode attributes.