Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

Try Vanilla Forums Cloud product

Custom BBCodes

R_JR_J Cheerleader & TroubleshooterMunich Moderator

I have been asked how to create custom BBCodes and I've realized that I never saw anyone speaking about this/offering a solution.

Since it is really simple, here is an example together with some places to look for information.

If you are the "first I learn before I do something" type of coder, here is some food for yor brain:
http://nbbc.sourceforge.net/doc/usage_enh.html
http://nbbc.sourceforge.net/doc/app_rule.html
And if you are more the "let me get my hands dirty, the sooner the better!" type of coder, here are two files where you can find BBCode implementations:
/library/core/class.bbcode.php
/vendor/vanilla/nbbc/src/BBCodeLibrary.php

Even if you prefer looking at the files, you should take a quick glance on the documentation and read a little bit about validating the input so that you will not open security holes with your custom BBCodes.

Enough said, here is a small example plugin which adds a custom BBCode so that a [bgbox color="green"]Hooray![/box] will be shown as <span class="BGBox" style="background-color:green">Hooray!</span>

<?php

$PluginInfo['customBBCode'] = [
    'Name' => 'Custom BBCode',
    'Description' => 'Adds some custom BBCode tags.',
    'Version' => '0.1',
    'Author' => 'Robin',
    'RequiredApplications' => ['Vanilla' => '>=2.3'],
    'MobileFriendly' => true,
    'License' => 'MIT'
];

class CustomBBCodePlugin extends Gdn_Plugin {
    public function bbcode_afterBBCodeSetup_handler($sender, $args) {
        $nbbc = &$args['BBCode'];
        $nbbc->addRule(
            'bgbox',
            [
                'mode' => $nbbc::BBCODE_MODE_ENHANCED,
                'template' => '<span class="BGBox" style="background-color:{$color}">{$_content}</span>',
                'allow' => ['color' => '/[a-zA-Z]+/'],
                'default' => ['color' => 'yellow'],
                'class' => 'inline',
                'allow_in' => ['listitem', 'block', 'columns', 'inline', 'link']
            ]
        );
    }
}

The BBCode rule added here is really simple. For more complex examples please look at the two files mentioned above. Have fun!

Sign In or Register to comment.