In the previous article, we reviewed the previous articles regarding GET requests, the native PHP facilities for making requests, and reviewed WordPress wp_remote_post
API function along with the arguments that it offers.
In this article, we're going to make use of wp_remote_post
such that we're actually able to see it in action. Remember that this - like wp_remote_post
- is part of the HTTP API of which there are other functions worth reviewing.
But, for now, we're going to put wp_remote_post
to work.
Specifically, we're going to do the following:
- When the page loads, we're going to submit some information to a custom script
- The script will examine the information and return it to our page
- We'll then display the data on the page
Sure, it's a bit of a contrived example but it will give us the experience of creating a separate PHP script that can be used for operations triggered by the use of wp_remote_post
.
Anyway, for the purposes of this example, we are going to use the PHP $_SERVER
collection to log when the user has submitted their preference rather than require that they have logged in.
Finally, the source code will be made available on GitHub and accessible at the end of this series in the following article.
For now however, let's get started with working on the plugin.
Stubbing Out the Class
If you've been following any of my articles for the last several months, then you know that I am a fan of the singleton pattern, and that I typically use the same boilerplate for building my plugins.
To that end, a lot of this will be repetitive - that's okay, for now. The business logic - or core logic - of the plugin is what will change, so stay tuned.
Prepare the Plugin
In your wp-content/plugins directory, create a directory called wp-remote-post-example as this will be the name of our plugin. After that, all the following files:
- wp-remote-post-example.php
- class-wp-remote-post-example.php
- wp-remote-receiver.php
In wp-remote-post-example.php, add the following code:
<?php /** * Plugin Name: WP Remote Post Example * Plugin URI: http://tommcfarlin.com/wp-remote-post/ * Description: An example plugin demonstrating how to use <code>wp_remote_post</code>. * Version: 1.0.0 * Author: Tom McFarlin * Author URI: http://tommcfarlin.com * License: GPL-2.0+ * License URI: http://www.gnu.org/licenses/gpl-2.0.txt */ // If this file is called directly, abort. if ( ! defined( 'WPINC' ) ) { die; } require_once( plugin_dir_path( __FILE__ ) . 'class-wp-remote-post.php' ); WP_Remote_Post_Example::get_instance(); "
Then, in class-wp-remote-post-example.php add the following code:
<?php class WP_Remote_Post_Example { protected static $instance = null; private function __construct() { } public static function get_instance() { if ( null == self::$instance ) { self::$instance = new self; } return self::$instance; } } "
Finally, add the following line to wp-remote-receiver.php:
<?php echo "<h4>The Post Data</h4>"; echo "<ul>"; foreach( $_POST as $key => $value ) { echo "<li>" . $key . ": " . $value . "</li>"; } echo "</ul>"; echo "<p>You can now save or disregard this information, </p>"; "
Notice that we're going to be iterating through the list of $_POST
data and displaying it in a list format that makes it easy to read.
Note that for the sake of space, I'm leaving code comments out of this particular plugin. The downloadable file on GitHub will be fully documented and will also be available in the next post.
At this point, you should be able to activate the plugin; however, nothing will actually happen upon activation besides than seeing a successful message.
This is good!
Get the Request Information
At this point, let's gather the information that we want to send as part of the request. Specifically, let's get the following:
- The unique address of the visitor
- The address of the homepage for the blog
- The address of the page that's being visited
Add the following line into the constructor (the private __construct
function, that is - not the public get_instance
function):
add_action( 'the_content', array( $this, 'get_post_response' ) );
Next, add the following function to the class:
public function increment_visitor_count( $content ) { if ( is_single() ) { $unique_id = $_SERVER['REMOTE_ADDR']; $site_url = site_url(); $page_url = get_permalink(); } return $content; }
Here, we're grabbing the unique ID from the REMOTE_ADDR
index of the $_SERVER
collection, we're grabbing the site URL as defined by WordPress, and then we're storing the permalink of the current page into its own variable.
Make the Request
At this point, we're ready to make the request. Recall from the previous article that there are several pieces of information we need to send along with the request:
- The URL
- The content of the body (which we'll use as the Unique ID, the Address, and the Page Viewed
Easy enough, right?
So let's continue updating our function above with the following block of code so that the function now looks like this:
public function increment_visitor_count( $content ) { if ( is_single() ) { $unique_id = $_SERVER['REMOTE_ADDR']; $site_url = site_url(); $page_url = get_permalink(); $url = plugins_url( 'wp-remote-post-example/wp-remote-receiver.php' ); $response = wp_remote_post( $url, array( 'body' => array( 'unique-id' => $unique_id, 'address' => $site_url, 'page-viewed' => $page_url ) ) ); } return $content; }
At this point, you should be able to reload the page though you won't necessarily see anything happen.
Even still, it's nothing too complicated, right?
Display the Result
At this point, assuming everything is wired up correctly, now we can display the results.
To do this, we'll need to first check to see if an error exists then display a message if so; otherwise, we'll display the results of the post request.
Add the following conditional to the function above directly under the wp_remote_post
call:
if ( is_wp_error( $response ) ) { $html = '<div id="post-error">'; $html .= __( 'There was a problem retrieving the response from the server.', 'wprp-example' ); $html .= '</div><!-- /#post-error -->'; } else { $html = '<div id="post-success">'; $html .= '<p>' . __( 'Your message posted with success! The response was as follows:', 'wprp-example' ) . '</p>'; $html .= '<p id="response-data">' . $response['body'] . '</p>'; $html .= '</div><!-- /#post-error -->'; } $content .= $html;
Note that we're opting to append some HTML based on the response that will display at the bottom of the post.
The Current Working Version
At this point, the current working version of the plugin should look like this:
<?php class WP_Remote_Post_Example { protected static $instance = null; private function __construct() { add_action( 'the_content', array( $this, 'get_post_response' ) ); } public static function get_instance() { if ( null == self::$instance ) { self::$instance = new self; } return self::$instance; } public function get_post_response( $content ) { if ( is_single() ) { $unique_id = $_SERVER['REMOTE_ADDR']; $site_url = site_url(); $page_url = get_permalink(); $url = plugins_url( 'wp-remote-post-example/wp-remote-receiver.php' ); $response = wp_remote_post( $url, array( 'body' => array( 'unique-id' => $unique_id, 'address' => $site_url, 'page-viewed' => $page_url ) ) ); if ( is_wp_error( $response ) ) { $html = '<div id="post-error">'; $html .= __( 'There was a problem retrieving the response from the server.', 'wprp-example' ); $html .= '</div><!-- /#post-error -->'; } else { $html = '<div id="post-success">'; $html .= '<p>' . __( 'Your message posted with success! The response was as follows:', 'wprp-example' ) . '</p>'; $html .= '<p id="response-data">' . $response['body'] . '</p>'; $html .= '</div><!-- /#post-error -->'; } $content .= $html; } return $content; } }
In the next, and final post in this series, we'll work on making the information appended to the bottom of the post look a little neater through the use of LESS for CSS just to get some experience with that, and to continue improving the way the plugin looks.
We'll also make sure that the plugin is fully documented and available on GitHub for further review.
Until then, tinker around with what we've covered here and we'll have more to share in the final article.
Comments