【问题标题】:timber context filter inside add_shortcode functionadd_shortcode 函数内的木材上下文过滤器
【发布时间】:2019-03-08 05:54:01
【问题描述】:

我一直在尝试在添加短代码功能中访问木材上下文,但它似乎不起作用。

我的代码是 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 \Timber\Timber::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 函数内添加过滤器,它可以工作,但它不在 add_shortcode 函数内,该函数也在 create_shortcodes 函数内。

任何帮助将不胜感激。 谢谢

【问题讨论】:

    标签: wordpress timber


    【解决方案1】:

    渲染返回的输出而不是在短代码中渲染它会更好吗?

    $returned_shortcode = do_shortcode('[your_shortcode]');
    
    return \Timber\Timber::compile('social-media.twig', array('data' => $returned_shortcode ));
    

    【讨论】:

      【解决方案2】:

      当你使用这条线时

      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 \Timber\Timber::compile( 'social-media.twig', $context );
      }
      

      除了您的自定义 data,您的 Twig 文件中还可以使用全局上下文。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-09-24
        • 2017-06-25
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多