我一直在尝试访问添加短代码函数中的木材上下文,但似乎不起作用。
我的代码是 add_action('init',array($ this,'create_shortcodes'((;
public function create_shortcodes() {
add_shortcode( 'social_media', array($this, 'social_shortcode') );
}
public function social_shortcode($atts) {
$params = shortcode_atts(array(
'id' => 0
), $atts);
$data = Helpers::create_social_media( $atts['id'], false, true );
add_filter( 'timber_context', array($this, 'add_to_context_social_media'), 11 );
return TimberTimber::compile('social-media.twig', array('data' => $data['content'] ));
}
public function add_to_context_social_media($context) {
echo '<pre style="margin:200px">';
print_r($context);
echo '</pre>';
return $context;
}
如果我在create_shortcodes函数中添加了过滤器,则它并不是在create_shortcodes函数中的add_shortCode函数。
任何帮助将不胜感激。谢谢
更好地渲染返回的输出而不是在短代码中渲染它?
$returned_shortcode = do_shortcode('[your_shortcode]');
return TimberTimber::compile('social-media.twig', array('data' => $returned_shortcode ));
使用此行
add_filter( 'timber_context', array($this, 'add_to_context_social_media'), 11 );
然后,您需要调用Timber::get_context()
才能应用过滤器。但是,对Timber::get_context()
的呼叫被缓存。这意味着,如果您想使用timber_context
过滤器,则必须在第一次调用Timber::get_context()
之前添加它。如果您想在短代码中使用它,则可能已经在显示帖子内容的单数或存档PHP模板中调用Timber::get_context()
。
我想您可以为您的 Social-Media.twig 模板建立数据上下文,如下所示:
public function social_shortcode($atts) {
$params = shortcode_atts(array(
'id' => 0
), $atts);
// Get cached context.
$context = Timber::get_context();
// Add to context.
$context['data'] = Helpers::create_social_media(
$atts['id'],
false,
true
);
return TimberTimber::compile( 'social-media.twig', $context );
}
除了您的自定义data
外,您还可以在树枝文件中使用全局上下文。