Timber - 将数据扩展到上下文(WordPress)上下文、扩展到、数据、Timber

2023-09-07 00:44:29 作者:恋爱无限期

所以我试图让这个函数的数据在每个上下文中都可用,但是我一直坚持如何实际获取数据本身,因为它是上下文的一部分.

So I'm trying to make this functions data available to each context there this, but I'm stuck with how to actually get the data itself now that its part of the context.

我有以下几点:

add_filter( 'timber_context', 'fancySquares_get_instagram_images'  );

 function fancySquares_get_instagram_images( $context ) {

  $context['instaImages'] = [];

  $api = wp_remote_request("testUrlHere");
  $api = json_decode($api['body']);


  for($i = 0; $i < 20; $i++)
    {
      $images[$i] = [];
      $images[$i]['image'] = $api->data[$i]->images->standard_resolution->url;
      $images[$i]['url'] = $api->data[$i]->link;
      $images[$i]['likes'] = $api->data[$i]->likes->count;
    }

    return $context;

}

我是他们试图打印出结果以确保我做对了,它返回一个空的 Array():

I am them trying to print out the result to make sure I'm doing it right, it returns an empty Array():

{{ instaImages|print_r}}

任何帮助将不胜感激.谢谢!

Any help would be appreciated. Thank you!

推荐答案

这里是针对上述问题的,希望对以后的人有所帮助.

Here is the for the above question, hope this helps someone in the future.

您将添加过滤器:

在传递给过滤器的函数中,您需要将 CONTEXT 变量设置为运行所有魔法的函数然后返回 CONTEXT,以便您可以自行决定在整个网站中使用它

代码示例:

add_filter( 'timber_context', 'fancySquares_show_instagram_results'  );

function fancySquares_show_instagram_results( $context ) {
    $context['fancySquaresInstagram'] = fancySquares_get_instagram();
    return $context;
}


function fancySquares_get_instagram()
{
  if(get_transient('instagram')) 
    {
        return get_transient('instagram');
    } 
    else 
    {
      $api = wp_remote_request("instagram-api-url");
      $api = json_decode($api['body']);
      $images = [];

      for($i = 0; $i < 20; $i++)
      {
        $images[$i] = [];
        $images[$i]['image'] = $api->data[$i]->images->standard_resolution->url;
        $images[$i]['url'] = $api->data[$i]->link;
        $images[$i]['likes'] = $api->data[$i]->likes->count;
      }


        set_transient('instagram', $images, 60*60*24); // expires every day
        return $images;
    }

}

然后您将输出:

{% for insta in fancySquaresInstagram %}

    {{insta['url']}}

  {% endfor %} 

或者可以打印整个内容以更好地了解里面的内容:

or could print the whole thing to get a better idea of whats inside:

{{ fancySquaresInstagram|print_r }}