Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

Already on GitHub? Sign in to your account

Added functionality to use native WordPress function to handle caching an #1

Closed
wants to merge 1 commit into
from
Jump to file or symbol
Failed to load files and symbols.
+29 −3
Split
View
@@ -40,6 +40,9 @@ class googleCard
// cache file name
public $cache_file = '';
+ // if this class is called from WordPress, for using native WP functions for better compatibility.
+ public $is_wp = false;
+
// constructor
function __construct($id = '')
{
@@ -54,8 +57,17 @@ function __construct($id = '')
// main handler function, call it from your script
public function googleCard()
{
+ // use native WP functionality rather than cache file
+ if(true === $this->is_wp) {
+ if (false === ($html = get_transient('googleCards'))) {
+ // no trasient found so fetch data and create new one
+ $html = $this->parseHtml();
+ set_transient('googleCards', $html, 60*60*$cache_hours);
+ }
+ return $html;
+ }
// if we're using caching
- if ($this->cache_data > 0)
+ elseif ($this->cache_data > 0)
{
$html = $this->ghettoCache();
return $html;
@@ -72,7 +84,11 @@ public function googleCard()
protected function parseHtml()
{
// load the page
- $this->getPage();
+ if($this->is_wp) {
+ $this->getWPPage();
+ } else {
+ $this->getPage();
+ }
// parse the html to look for the h4 'have X in circles' element
preg_match('/<h4 class="a-c-ka-Sf">(.*?)<\/h4>/s', $this->html, $matches);
@@ -100,7 +116,17 @@ protected function parseHtml()
return $return;
}
-
+ // use WordPress native functions to retrieve data rather than curl
+ protected function getWPPage() {
+ $response = wp_remote_get($this->url, array('user-agent' => $this->user_agent, 'sslverify' => false));
+ // if there happens to an error fall back to curl
+ if(is_wp_error($response)) {
+ $this->getPage();
+ } else {
+ $this->html = $response['body'];
+ }
+ }
+
// use curl to load the page
protected function getPage()
{