I’ve been firefighting this for a while and I’m struggling with getting this shortcode to render this Twig partial when it is called. Anyone have any advice?
Thanks!
Here’s what I have so far:
<?php namespace locwplib;
use Timber as Timber;
use Twig_SimpleFunction as Twig_SimpleFunction;
class LOCShortcodes {
public function addSlider() {
add_shortcode('feature-slider', 'feature_slider');
function feature_slider() {
return Timber::render('template-feature-slider.twig');
}
}
}
When you work with hooks and filters (or shortcodes in your case) in a class context, you need to define the callback a little differently.
The last example in https://codex.wordpress.org/Function_Reference/add_shortcode shows you how you use shortcodes with classes:
As you can see, the shortcode is added outside of the class. If you want to add it inside your class, then you don’t have to explicitly use the name of the class, but you can use
$this
:In your case, you could do it like this:
Don’t forget to use
Timber::compile()
instead ofTimber::render()
, because therender()
function is echoing the output, while for shortcodes, the output should be returned. This is also mentioned in the Notes section in the Codex:Also make sure to read the wiki section about Shortcodes in Timber.