| 1 |
<?php |
| 2 |
if ( ! defined( 'ABSPATH' ) ) exit; // Exit if accessed directly |
| 3 |
|
| 4 |
class HTMega_Menu_Api { |
| 5 |
|
| 6 |
/** |
| 7 |
* Define necessary variables |
| 8 |
*/ |
| 9 |
const REMOTE_BASE_URL = 'https://feed.hasthemes.com/notices/news-feed'; |
| 10 |
// const REMOTE_BASE_URL = 'http://news-feed.test'; // local dev — swap back before release |
| 11 |
const ENDPOINT_FILE = 'news-data.json'; |
| 12 |
const TRANSIENT_KEY = 'htmega_menu_news_feed_data'; |
| 13 |
|
| 14 |
/** |
| 15 |
* Get news feed data. |
| 16 |
* Retrieve the banner + feed data from the HasThemes news-feed server. |
| 17 |
* |
| 18 |
* @param bool $force_update Optional. Whether to force the data update. |
| 19 |
* @return array News Feed data ( 'banner' => [...], 'feed' => [...] ). |
| 20 |
*/ |
| 21 |
public static function get_remote_data( $force_update = false ) { |
| 22 |
$cache_key = self::TRANSIENT_KEY; |
| 23 |
|
| 24 |
$info_data = get_transient( $cache_key ); |
| 25 |
|
| 26 |
if ( $force_update || false === $info_data ) { |
| 27 |
$timeout = ( $force_update ) ? 25 : 8; |
| 28 |
|
| 29 |
$response = wp_remote_get( sprintf( '%s/%s', self::REMOTE_BASE_URL, self::ENDPOINT_FILE ), [ |
| 30 |
'timeout' => $timeout, |
| 31 |
] ); |
| 32 |
|
| 33 |
if ( is_wp_error( $response ) || 200 !== (int) wp_remote_retrieve_response_code( $response ) ) { |
| 34 |
set_transient( $cache_key, [], HOUR_IN_SECONDS ); |
| 35 |
return []; |
| 36 |
} |
| 37 |
|
| 38 |
$info_data = json_decode( wp_remote_retrieve_body( $response ), true ); |
| 39 |
|
| 40 |
if ( empty( $info_data ) || ! is_array( $info_data ) ) { |
| 41 |
set_transient( $cache_key, [], HOUR_IN_SECONDS ); |
| 42 |
return []; |
| 43 |
} |
| 44 |
|
| 45 |
set_transient( $cache_key, $info_data, 12 * HOUR_IN_SECONDS ); |
| 46 |
} |
| 47 |
|
| 48 |
return empty( $info_data ) ? [] : $info_data; |
| 49 |
} |
| 50 |
|
| 51 |
} |
| 52 |
|