Fallback Shortcode
tanftw opened this issue · comments
Hi, I'm creating shortcode for my project. It useful when we can have default shortcode. Imagine when we use WordPress, we want to retrieve any post field (included post meta value which can be any string). It's awesome when we can do something like this:
$handler->add('*', function (ShortcodeInterface $s) {
$shortcode_name = $s->getName();
return get_post_meta(get_the_ID(), $shortcode_name, true);
});
So if we have a post with a field country
and value is Hong Kong
, when we run [country]
shortcode, it returns Hong Kong.
Currently, I can achieve it with your Event, like so:
$events = new \Thunder\Shortcode\EventContainer\EventContainer();
$events->addListener(\Thunder\Shortcode\Events::FILTER_SHORTCODES, function (\Thunder\Shortcode\Event\FilterShortcodesEvent $event) use ($handler) {
$shortcodes = $event->getShortcodes();
foreach ($shortcodes as $shortcode) {
$handler->add($shortcode->getName(), function ($s) {
$shortcode_name = $s->getName();
return get_post_meta(get_the_ID(), $shortcode_name, true);
});
}
});
Hi, @tanftw, please take a look at HandlerContainer::setDefault(). If you set a default handler in the container it will be called for all unregistered shortcodes in the parsed text. You can do the same thing you wrote in your example without using events. Side note: what you wrote in the example is quite clever, I never used events for that. :)
Please let me know if that was what you've been asking for. You can close the issue or ask more questions, I'm always happy to help. Thanks!
Awesome bro! Thats exactly what I need.
No problem, I'm happy that you're happy! 😄