当前位置:首页>WordPress建站>WordPress开发>WordPress HTTP API 指南:wp_remote_post 实例

WordPress HTTP API 指南:wp_remote_post 实例

WordPress 主题 CoreNext

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

<?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 __constructfunction, that is – not the publicget_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.

您已阅读完《WordPress HTTP API 指南(共8篇)》专题的第 6 篇。请继续阅读该专题下面的文章:

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。

给TA打赏
共{{data.count}}人
人已打赏
欢迎关注WordPress大学公众号 WPDAXUE
WordPress开发

WordPress HTTP API 指南:wp_remote_post 概述

2016-6-18 10:15:27

WordPress开发

WordPress HTTP API 指南:从 wp_remote_post 保存数据

2016-6-19 11:05:29

0 条回复 A文章作者 M管理员
    暂无讨论,说说你的看法吧
个人中心
购物车
优惠劵
今日签到
有新私信 私信列表
搜索