Как добавить кеширование для предотвращения ошибки http 508? - PullRequest
0 голосов
/ 02 июля 2019

Я создал плагин, который загружает 30 случайно сгенерированных имен + картинок, используя API от uinames.com. Плагин работает отлично и отображает, что он должен.Вот так:

enter image description here

Но каждые несколько раз, когда я обновляюсь, я получаю следующее:

Warning
: file_get_contents(https://uinames.com/api/?amount=30&region=Netherlands&ext): failed to open stream: HTTP request failed! HTTP/1.1 508 Loop Detected in
C:\xampp\htdocs\wordpress\wp-content\themes\twentynineteen\functions.php

Теперь я долженЧтобы решить эту проблему с помощью кэширования, я следовал нескольким учебникам, но не совсем понял

Мой код:

class PHP_Widget_wpse_12345 extends WP_Widget {
    function __construct() {
        $opts = array(
          'description' => 'Display catfish'
        );
        parent::WP_Widget(
          'test',
          'catfish list',
          $opts
        );
    }
    function widget($args,$instance) {
        $persons = json_decode(file_get_contents('https://uinames.com/api/?amount=30&region=Netherlands&ext'));
        $widget_content = "";

        foreach($persons as $person) {
            $widget_content .= $person->name . ' ' . $person->surname . "<br>" . "<br/> <img src='$person->photo'> <br/>";        
    }           

                echo $widget_content;
    }
}

    function register_my_widgets() {
        register_widget('PHP_Widget_wpse_12345');
    }
add_action('widgets_init','register_my_widgets');

Любая помощь приветствуется!

1 Ответ

0 голосов
/ 02 июля 2019

Метод, который вы можете использовать:

set a flag ($reload = true) to test whether or not to get new file
if the cache file exists
   get the date/time of the cache file
   is the time > refresh time limit
   if yes - set the reload flag to true
   if no  - set the reload flag to false
if reload flag = false
   open file and get contents
otherwise
   get info from the external web site
   get the contents 
   save the contents to cache file
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...