Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a Wordpress shortcode-style function in PHP

I am trying to create a Wordpress shortcode-style feature in PHP to replace shortcodes like "[[133]]" with images. Basically, I have a MySQL table of image URLs/titles/subtitles with IDs 1-150, and I want to be able to dynamically insert them into the text of my pages with shortcodes like this:

Blabla bla bla bla bla. [[5]] Also, bla bla bla bla bla [[27]] Hey, and bla bla bla! [[129]]

So, I just want to grab the ID as $id, and then feed it to a MySQL query like mysql_query("SELECT title,subtitle,url FROM images WHERE id = $id") and then replace the "[[id]]" with the img/title/subtitle. I would like to be able to do this multiple times on the same page.

I know this has to involve regex and some combination of preg_match, preg_replace, strstr, strpos, substr... but I don't know where to start and which functions I should be using to do which things. Can you recommend a strategy? I don't need the code itself—just knowing what to use for which parts would be extremely helpful.

like image 241
supertrue Avatar asked Dec 31 '10 06:12

supertrue


1 Answers

If you want to be able to write shortcodes like this :

[[function_name_suffix parameter1 parameter2 ...]]

here is a more complete way, using preg_replace_callback and call_user_func_array to implement parameterized shortcodes.

function shortcodify($string){
    return preg_replace_callback('#\[\[(.*?)\]\]#', function ($matches) {
        $whitespace_explode = explode(" ", $matches[1]);
        $fnName = 'shortcode_'.array_shift($whitespace_explode);
        return function_exists($fnName) ? call_user_func_array($fnName,$whitespace_explode) : $matches[0];
    }, $string);
}

If this function is defined :

function shortcode_name($firstname="",$lastname=""){
    return "<span class='firstname'>".$firstname."</span>&nbsp;<span class='lastname'>".$lastname."</span>";
}

Then this call

print shortcodify("My name is [[name armel larcier]]");

Will output :

My name is <span class='firstname'>armel</span>&nbsp;<span class='lastname'>larcier</span>

This is just something I implemented right now based on supertrue's idea.

Any feedback is more than welcome.

like image 58
Armel Larcier Avatar answered Sep 27 '22 23:09

Armel Larcier