How do I use shortcodes in a standard PHP page?

I want to use a WordPress style shortcode in my own CMS. For example, with Embedded Tweets, I can say:

[tweet 'TWEET URL']

Read More

and the tweet will be embedded with the standard format as supplied by Twitter. Similarly with YouTube videos:

[youtube 'YOUTUBE VIDEO']

will embed the YouTube video player. How would I do that with PHP and MySQL? I am not looking for a ‘generic’ system; manually adding shortcodes would work just fine with me, as long as I know what I am doing.

Related posts

Leave a Reply

2 comments

  1. WordPress has a fairly elaborate scheme for processing post/page content in the dbms and depositing it in the output stream. Part of that involves scanning the text for registered shortcodes and replacing them with the appropriate URLs or other text.

    The WordPress Codex explains how to write a plugin to implement a shortcode. There are plenty of examples to look at.

    http://codex.wordpress.org/Shortcode_API

    But if you’re going to immplement this in your own CMS you need to build your own scheme for processing content, and tie processing into it.

  2. If you have the ability to install custom extensions from PECL, i would suggest the BBCode Extension for PHP.

    Example from the official documentation:

    <?php
    $arrayBBCode=array(
        ''=>         array('type'=>BBCODE_TYPE_ROOT,  'childs'=>'!i'),
        'i'=>        array('type'=>BBCODE_TYPE_NOARG, 'open_tag'=>'<i>',
                        'close_tag'=>'</i>', 'childs'=>'b'),
        'url'=>      array('type'=>BBCODE_TYPE_OPTARG,
                        'open_tag'=>'<a href="{PARAM}">', 'close_tag'=>'</a>',
                        'default_arg'=>'{CONTENT}',
                        'childs'=>'b,i'),
        'img'=>      array('type'=>BBCODE_TYPE_NOARG,
                        'open_tag'=>'<img src="', 'close_tag'=>'" />',
                        'childs'=>''),
        'b'=>        array('type'=>BBCODE_TYPE_NOARG, 'open_tag'=>'<b>',
                        'close_tag'=>'</b>'),
    );
    $text=<<<EOF
    [b]Bold Text[/b]
    [i]Italic Text[/i]
    [url]http://www.php.net/[/url]
    [url=http://pecl.php.net/][b]Content Text[/b][/url]
    [img]http://static.php.net/www.php.net/images/php.gif[/img]
    [url=http://www.php.net/]
    [img]http://static.php.net/www.php.net/images/php.gif[/img]
    [/url]
    EOF;
    $BBHandler=bbcode_create($arrayBBCode);
    echo bbcode_parse($BBHandler,$text);
    ?>
    

    Would return:

    <b>Bold Text</b>
    [i]Italic Text[/i]
    <a href="http://www.php.net/">http://www.php.net/</a>
    <a href="http://pecl.php.net/"><b>Content Text</b></a>
    <img src="http://static.php.net/www.php.net/images/php.gif" />
    <a href="http://www.php.net/">
    [img]http://static.php.net/www.php.net/images/php.gif[/img]
    </a>
    

    If you can’t install the extension, look at this PHP Library which you can include in user-land code.