Create my own shortcode with php

Robert picture Robert · Nov 27, 2012 · Viewed 13k times · Source

I want create my own shortcode

In the text i can put the shortcode for example :

The people are very nice , [gal~route~100~100] , the people are very nice , [ga2l~route2~150~150]

In this expression you can see the shortcodes into [ ] tags , i want show the text without this shortcodes and replace it for gallery ( with php include and read the path gallery from shortcode)

I think use this method , as you can see down , but none of them works for me , however people here can tell me something or give me any idea which can help me

 <?php
 $art_sh_exp=explode("][",html_entity_decode($articulos[descripcion],ENT_QUOTES));

 for ($i=0;$i<count($art_sh_exp);$i++) {

 $a=array("[","]"); $b=array("","");

 $exp=explode("~",str_replace ($a,$b,$art_sh_exp[$i]));


 for ($x=0;$x<count($exp);$x++) { print
 "".$exp[1]."-".$exp[2]."-".$exp[3]."-<br>"; }

 } ?>

Thanks

Answer

emartel picture emartel · Nov 27, 2012

I suggest you use a regular expression to find all occurrences of your shortcode pattern.

It uses preg_match_all (documentation here) to find all the occurrences and then simple str_replace (documentation here) to put the transformed shortcode back in the string

The regular expression contained in this code simply tries to match 0 to unlimited occurences of a character between brackets [ and ]

$string = "The people are very nice , [gal~route~100~100] , the people are very nice , [ga2l~route2~150~150]";
$regex = "/\[(.*?)\]/";
preg_match_all($regex, $string, $matches);

for($i = 0; $i < count($matches[1]); $i++)
{
    $match = $matches[1][$i];
    $array = explode('~', $match);
    $newValue = $array[0] . " - " . $array[1] . " - " . $array[2] . " - " . $array[3];
    $string = str_replace($matches[0][$i], $newValue, $string);
}

The resulting string is now

The people are very nice , gal - route - 100 - 100 , the people are very nice , ga2l - route2 - 150 - 150

By breaking the problem in 2 phases

  • Finding all occurrences
  • Replacing them with new values

It is simpler to develop and debug. It also makes it easier if you want to change at one point how your shortcodes translate to URLs or whatever.

Edit: as suggested by Jack, using preg_replace_callback would allow to do that simpler. See his answer.