Version 1.0
- Just a single file
- No dependencies
- Very easy to use
- Shortcodes supports single, double and literal quotes
The code below is a fully working example.
include __DIR__ . '/shortcode.php';
shortcode::add('button', function($args) {
return '<a href="' . $args->url . '">' . $args->title . '</a>';
});
echo shortcode::filter('<p>[button title="About" url="about"]</p>');
Include the shortcode.php
file. Just make sure the path is correct.
include __DIR__ . '/shortcode.php';
A shortcode starts with [
and ends with ]
. The whole shortcode will then be replaced with the output from your custom method.
[button]
Single quotes can be used inside the double quotes.
[button title="It's a button" url="about"]
Double quotes can be used inside single quotes.
[button title='My "button"' url='about']
Both single and double quotes can be used inside template literals.
[button title=`It's my "button"` url='about']
With a custom method, you will replace the shortcode with your custom method output.
name
- The name of the shortcode [button
title="button"]method
- The output of the method will replace the shortcode.args
(optional) - Arguments sent from the shortcode.types
(optional) - The type of quotes that was used for each argument.
shortcode::add('button', function() {
return 'Hello!';
});
shortcode::add('button', function($args) {
return '<a href="' . $args->url . '">' . $args->title . '</a>';
});
Your shortcode quotes may vary from time to time.
[quote content='"I am a quote"']
[quote content="'I am a quote'"]
If you are not always using the same type of quotes, you may need to use the second optional parameter $quotes
.
shortcode::add('quote', function($args, $quotes) {
return sprintf('
<div data-content=%s%s%s></div>',
$quotes->content,
$args->content,
$quotes->content,
);
});
All shortcodes will be replaced with the output from your custom method.
$html = '<p>[button]</p>';
echo shortcode::filter($html);
When using shortcode::add()
or $shortcode->add()
, your custom method will be added to a global variable for later usage.
With unset()
and unsetAll()
, you can remove one or remove all of them.
Remove a single custom method from memory by shortcode name.
shortcode::unset('button');
Remove all custom methods from memory.
shortcode::unsetAll();
With all methods you can use an instantiated class instead if you prefer that approach.
$shortcode = new PHPShortcode();
echo $shortcode->filter('[button]');
To prevent breaking HTML, it can sometimes be good to convert quotes to html characters.
$some_argument = htmlspecialchars($args->some_argument, ENT_QUOTES);
- Support for usage without quotes, mainly for integers.
- You can't place content within a start and closing shortcode like
[hello]world[/hello]
... yet. - You can't use line breaks inside shortcodes. However, it's fine to print out line breaks from the custom shortcode methods.
Can you break it? If you break it in an unexpected way, please report it as a bug to us. Provide a code example.
MIT