WordPress HTTP API 指南:wp_remote_post 實例

本文是《WordPress HTTP API 指南》專題的第 6 篇,共 8 篇:

在前面的文章中,我們回顧了 GET 請求,使用 PHP 原生功能來發起請求,以及概覽了 WordPress wp_remote_post API 函數及所提供的參數。

本文將在實際中使用 wp_remote_post 以便了解它是如何具體工作的。請記住,wp_remote_post 只是 HTTP API 中的一部分,還有其他類似函數等待我們學習。

注:由于時間精力有限,本教程沒辦法翻譯分享,希望朋友們可以加入我們,幫助我們進行翻譯,有小酬謝,有意者請聯系倡萌QQ 745722006(注明:教程翻譯)。

以下為原文:http://code.tutsplus.com/tutorials/a-look-at-the-wordpress-http-api-a-practical-example-of-wp_remote_post--wp-32425

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:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
<?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:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
<?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:

1
2
3
4
5
6
7
8
9
10
11
<?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 __constructfunction, that is - not the publicget_instance function):

1
add_action( 'the_content', array( $this, 'get_post_response' ) );

Next, add the following function to the class:

1
2
3
4
5
6
7
8
9
10
11
12
13
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:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
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:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
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:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
<?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.

聲明:本站所有文章,如無特殊說明或標注,均為本站原創發布。任何個人或組織,在未征得本站同意時,禁止復制、盜用、采集、發布本站內容到任何網站、書籍等各類媒體平臺。如若本站內容侵犯了原著者的合法權益,可聯系我們進行處理。
歡迎關注我們的微信公眾號:WPDAXUE

倡萌

一個文科IT宅男,喜歡折騰WordPress和被它折騰 ^_^

暫無評論

發表評論