当您在类上下文中使用钩子和过滤器(或您的案例中的短代码)时,您需要稍微不同地定义回调。
https://codex.wordpress.org/Function_Reference/add_shortcode中的最后一个示例向您展示了如何将短代码与类一起使用:
<?php
class MyPlugin {
public static function baztag_func( $atts, $content = "" ) {
return "content = $content";
}
}
add_shortcode( 'baztag', array( 'MyPlugin', 'baztag_func' ) );
如您所见,短代码是在课程之外添加的。如果要将其添加到类中,则不必显式使用类的名称,但可以使用$this
:
<?php
class MyPlugin {
public function __construct() {
add_shortcode( 'baztag', array( $this, 'baztag_func' ) );
}
public static function baztag_func( $atts, $content = "" ) {
return "content = $content";
}
}
在您的情况下,您可以这样做:
<?php
class LOCShortcodes {
public function __construct() {
add_shortcode( 'feature-slider', array( $this, 'feature_slider' ) );
}
public function feature_slider() {
return Timber::compile( 'template-feature-slider.twig' );
}
}
不要忘记使用Timber::compile()
而不是Timber::render()
,因为该render()
函数正在回显输出,而对于短代码,应该返回输出。Codex的注释部分也提到了这一点:
请注意,短代码调用的函数不应产生任何类型的输出。简码函数应返回用于替换简码的文本。直接产生输出会导致意想不到的结果。[…]
还要确保阅读有关Timber 中的 Shortcodes的 wiki 部分。