I have a class ‘wp_php_flickr’ which will use the wordpress core class ‘WP_HTTP’ in a plugin which i’m writing
if( !class_exists( 'WP_Http' ) ) {
require_once( WP_INSTALL_DIR.'wp-includesclass-http.php');
}
class wp_php_flickr {
...
}
As i’m testing i’m noticing that i am required to include more and more core classes, which the WP_HTTP class is dependent on
require_once( WP_INSTALL_DIR.'wp-includesplugin.php');
require_once( WP_INSTALL_DIR.'wp-includesgeneral-template.php');
require_once( WP_INSTALL_DIR.'wp-includeslink-template.php');
require_once( WP_INSTALL_DIR.'wp-includesoption.php');
require_once( WP_INSTALL_DIR.'wp-includescache.php');
I’m wondering is there a smarter or better way to ensure the required dependent classes are available automatically to my class?
Prerequisites
First, all your callbacks (alias: runtime functions/methods) should be attached to predictable hooks. Example:
This callback is attached to the first hook that is available for plugins. Now other plugins know when your plugin is loading and attaching hooks.
You will want to wrap all those tasks you perform into methods in your class and attach them to your bootstrap/constructor method. In there you attach those methods to hooks.
Running HTTP remote requests
The WP HTTP API provides a handy set of public API functions and filters that you can use to do your requests.
First you might want to use one of the following functions depending on what you need:
wp_remote_get()
wp_remote_post()
wp_remote_head()
wp_remote_request()
The
wp_remote_head()
function normally is used to just test for availability or support for some requiredheader
.When you’re done with your request you’re able to test and validate if there was an error:
Now you got the response. The question remaining is what format it got. Just use the plain PHP functions like
json_decode()
for JSON responses,simplexml_load_string()
or similar for strings, etc.Finally it’s time to get the actual data.
The last task to do is – before touching the content and performing test if we got JSON, XML, XLS, CSV, etc. – some preparation. The first thing always is to do a
trim()
: Nearly every provider stuffs empty spaces around the response by accident.Full blown example
Now here’s an example that does two things:
Attach the data to a filter that you can use in templates to grab your data.
Now your able to do the following in your template: