简体   繁体   中英

Create my own shortcode with php

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

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.

One way to do this is by using preg_replace_callback() :

function my_replace($match)
{
    // $match[0] is e.g. "[gal~route~100~100]"
    // $match[1] is e.g. "gal~route~100~100"

    // now do whatever you want with the found match
    return join('-', explode('~', $match[1])) . '<br />';
}

// apply callback on all patterns like [*]
preg_replace_callback(
    '/\[([^]]+)\]/', 
    'my_replace',
    html_entity_decode($articulos[descripcion],ENT_QUOTES)
);

You could also try something like this:

$org_text = "Lorem ipsum dolor sit amet, [SHORTCODE_1] adipiscing elit.
Phasellus id orci ac dolor dapibus [SHORTCODE_1] at eu sem.
Nullam pretium bibendum urna et gravida. Donec [SHORTCODE_1] vehicula lectus
nec facilisis. Maecenas vel ante tincidunt, [SHORTCODE_2] 
sem id, tincidunt elit. Integer neque [SHORTCODE_2], ultrices in lore
[SHORTCODE_2], egestas ullamcorper enim.";

$shortcodes_a =  array('[SHORTCODE_1]','[SHORTCODE_2]');
$shortcodes_b =  array('Some text','Some other text');                   

$new_text = '';

$new_text = str_replace($shortcodes_a, $shortcodes_b, $org_text);

echo $new_text;

This will give you:

Lorem ipsum dolor sit amet, Some text adipiscing elit. Phasellus id orci ac dolor dapibus Some text at eu sem. Nullam pretium bibendum urna et gravida. Donec Some text vehicula lectus nec facilisis. Maecenas vel ante tincidunt, Some other text sem id, tincidunt elit. Integer neque Some other text, ultrices in lorem Some other text, egestas ullamcorper enim.

You could use Regular Expression to match the items inside the square brackets. And then explode() the string with delimiter as ~ to get the other values(or you could use Regular Expression for that too).

References:

preg_match()

preg_match_all()

preg_replace()

A good reference for learning Regular Expressions: http://www.regular-expressions.info/

I Saw this and it helped And thought if some one would like to know a more or less simple version finished to at least generate the cleaned up version of various shortcodes with a content block. [slideshow:(name of slideshow)] or [form:(name of form)] (I only set it up as far as the slide show bit so far and thought i'd try to give back. the code is below and can be simply copied into a php file and viewed to see what the output is.

<code>
//Regular expression  would be : '/\[(blah:)(.)+\]/'
// The \\2 is an example of backreferencing. This tells pcre that
// it must match the second set of parentheses in the regular expression
// itself, which would be the ([\w]+) in this case. The extra backslash is
// required because the string is in double quotes.
$html = "stupid text here taht is totally lame [slideshow:topLeft] Some more dumb text [slideshow:topright] and finally some more dumb text here.";

preg_match_all('/\[(slideshow:)(.*?)\]/', $html, $matches);
$properArray = array();
$customShortCodes = array();
foreach($matches[0] as $slideKey=>$slideShow)
{
    $matchNoBrackets = str_replace(array('[',']'),'',$slideShow);
    $shortCodeExploded = explode(':', $matchNoBrackets);
$customShortCodes['slideshow'][$slideKey] = $shortCodeExploded[1];
}
$customShortCodes['form'][0] = 'contact us';
$customShortCodes['form'][1] = 'Mulch Count';
//loop through customShortCodes to replace proper values.
$newContent = $html;//assigning original content to new only for comparison testing.
foreach($customShortCodes as $shortCodeKey=>$shortCode)
{
    if($shortCodeKey == 'slideshow')
    {
        print_r($shortCode);
        foreach($shortCode as $show)
        {
            $testingReplacementText = "<strong>$show</strong>";
            $originalShortCode = "[slideshow:$show]";
            $newContent = str_replace($originalShortCode,$testingReplacementText,$newContent);
        }
    }
    if($shortCodeKey == 'form')
    {
        //print_r($shortCode);
    }
}

print_r($customShortCodes);
</code>

Output from what is above:

  • Original: stupid text here taht is totally lame [slideshow:topLeft] Some more dumb text [slideshow:topright] and finally some more dumb text here.
  • Revized: stupid text here taht is totally lame topLeft Some more dumb text topright and finally some more dumb text here.

    echo 'Original: '.$html.'
    '; echo 'Revized: '.$newContent.'
    ';

I hope this helps. I created this with wordpress shortcodes in mind to use on my own cms. The Real end result will involve using ob_start and including php files to get the desired output.

<code>
ob_start();
include "{$slideshowName}_slideshow.php";//OR pass through params to the file...
$conditionalContent = ob_get_contents();
ob_end_clean();
</code>

your string replace parameter variables wont accept array values;

str_replace ($a,$b,$art_sh_exp[$i]) /*Here $a , $b are array values so wont work*/

Try using below method: 1. Frist try replacing the string character '[' 2. Then try replacing the string character ']'

Please try this;

str_replace (']','',str_replace ('[','',$art_sh_exp[$i]))
<code>
ob_start();
include "{$slideshowName}_slideshow.php";//OR pass through params to the file...
$conditionalContent = ob_get_contents();
ob_end_clean();
</code>

This will help you

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM