Timber - extend data to context (WordPress)

久未见 提交于 2019-12-10 11:58:39

问题


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.

I have the following:

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;

}

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!


回答1:


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

You'll add the filter:

  • inside the function passed to the filter, you'll set the CONTEXT variable to the function where you'll run all your magic
  • and then return the CONTEXT so you can use it throughout the site at your discretion

code sample:

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;
    }

}

You will then output with:

{% for insta in fancySquaresInstagram %}

    {{insta['url']}}

  {% endfor %} 

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

{{ fancySquaresInstagram|print_r }}


来源:https://stackoverflow.com/questions/47229352/timber-extend-data-to-context-wordpress

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!