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;
}
You can use
preg_replace_callback()
for that purpose. You’ll also need to wrapd+
in(
parentheses)
so it can be captured and used in the callback function.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.
@BoltClock’s answer is correct, but
create_function()
is a little old fashioned now.Pass the captured id to the helper function via an anonymous function inside of
preg_replace_callback()
.The helper function’s returned string will be used to replace the entire matched shortcode.
Since no limit was declared for
preg_replace_callback()
, it will make potentially multiple replacements.Code: (Demo)
Output:
P.s. As @azureru mentioned in a comment, this does seem like a good candidate for implementing WordPress’s shortcode api. http://codex.wordpress.org/Shortcode_API