WordPress HTTP API 指南:wp_remote_post 实例

一弯拱桥对映着一弯晓月,桥下流水波光粼粼,昙花一般的月,在我眼中异香腾风,秀色媚景。夜的静谧是风景,昼的明媚是风景。江花胜火红,寒山伤心碧,空伫玉阶白,西风残照黄。处处皆风景,处处皆绝妙风景。
本文是《WordPress HTTP API 指南》专题的第 6 篇,共 8 篇:
  • WordPress HTTP API 指南:wp_remote_get 概述
  • WordPress HTTP API 指南:wp_remote_get 实例
  • WordPress HTTP API 指南:wp_remote_get 响应
  • WordPress HTTP API 指南:wp_remote_get 参数
  • WordPress HTTP API 指南:wp_remote_post 概述
  • WordPress HTTP API 指南:wp_remote_post 实例
  • WordPress HTTP API 指南:从 wp_remote_post 保存数据
  • WordPress HTTP API 指南:回顾

在前面的文章中,我们回顾了 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();

<?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;

    }

}

<?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>";

<?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' ) );

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;

}

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;

}

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;

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;

    }

}

<?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.

到此这篇关于WordPress HTTP API 指南:wp_remote_post 实例就介绍到这了。目标和信念给人以持久的动力,它是人的精神支柱。更多相关WordPress HTTP API 指南:wp_remote_post 实例内容请查看相关栏目,小编编辑不易,再次感谢大家的支持!

标签: HTTP WordPress