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

本文是《WordPress HTTP API 指南》专题的第 7 篇,共 8 篇:

在前面的文章中,我们创建了一个小插件作为 wp_remote_post 的实例,但是这个实例还没有完成。


注:由于时间精力有限,本教程没办法翻译分享,希望朋友们可以加入我们,帮助我们进行翻译,有小酬谢,有意者请联系倡萌QQ 745722006(注明:教程翻译)。


In the previous post in the series, we began working on a small plugin that provided a practical example ofwp_remote_post. The thing is, the example was incomplete.

Sure, it's nice to see how to make a call using the function and even how to setup a script responsible for receiving the data and returning the data, but it's of little use unless we do anything with it.

In this final article in the series, we're going to revisit the plugin that we started with the last article and begin improving it a bit.

Specifically, we will...

  • Review what we've done
  • Begin making some changes to the work that we created in the last article
  • Style the presentation with LESS in order to keep some of our newer skills updated
  • Review the arguments accepted by both wp_remote_get and wp_remote_post

Finally, all of the work accomplished in this article will be available on GitHub and linked in the conclusion of the article. But before that, let's go ahead and get started.

What We've Done

In the previous article, we setup a basic plugin that would display information about the visitor to the current website:


Using information available via the server side, we're able to display the ID of the visitor, the address to which they navigated, and the page that's been viewed.

Easy stuff, right?

In order to make the code more readable, maintainable, and able to be styled, there are a few things we need to do. But first, if you've got gotten this far, review the previous article, implement the source code, then return to this post.

The Remote Receiver Revisited

Recall from the previous article, we introduced a file called wp-remote-received.php which was responsible for grabbing information from PHP's $_POST collection and building a view that was more user-friendly than a simple dump of the data.

Specifically, here's the code with which we were working:

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

But let's clean this up a little bit. Rather than echoing multiple statements, let's build up a single string of HTML then return it. Additionally, we'll provide some extra elements and class names that will make it easier to access via CSS:

// Build up the HTML display of of the data
$html = '<div id="wp-remote-post-example-container">';
    $html .= '<h4>The Post Data</h4>';
    $html .= '<ul>';
    foreach ( $_POST as $key => $value ) {
        $html .= '<li>' . $key . ': ' . $value . '</li>';
    } // end foreach
    $html .= '</ul>';
$html .= '</div><!-- /#wp-remote-post-example-container -->';
// Finally, echo the HTML to the requester
echo $html;

Nothing too complicated. In short, we added a wrapper with a unique ID, then placed everything within said wrapper. We also removed the sentence about whether or not the information could be saved.

View the page in your browser to double-check all things look the same. At this point, there should be no difference from the screenshot above.

If so, review your code.

Add Some Style

Before we move into actually serializing this information, let's continue by styling the information as provided by the receiver.

To do that, let's create a css directory in the root of the plugin directory. We'll also create a lesssubdirectory in which our plugin LESS file will reside. I'll call the file display.less since it's being used to, you know, style the display :).


Next, we'll add the entire plugin directory to CodeKit. If you're unfamiliar with how to do this, please reviewthis series.


At this point, we're ready to write a little bit of LESS to give our plugin a slightly better presentation.

Add the following code to your LESS file:

#wp-remote-post-example-container {
    background: #f7f5e7;
    border:     1px solid #ac0404;
    padding:    20px;
    h4 {
        margin: 0;
    } // h4
    ul {
        li {
            list-style-type: circle;
        } // li
    } // ul
} // /#wp-remote-post-example-container

CodeKit (or the LESS compiler if you opt to go that route) should generate the proper CSS. Next, we need to instruct our plugin to load up the new CSS file. To do this, add the following line of code to your constructor:

add_action( 'wp_enqueue_scripts', array( $this, 'add_style_sheet' ) );

Then, add the following function to your class:

public function add_style_sheet() {
    wp_enqueue_style( 'wp-remote-post-example-style', plugins_url( 'wp-remote-post-example/css/display.css' ) );
} // end add_style_seet

Finally, reload a single post and your page should look like this:


Looks good enough, right? Sure, you can customize it however you'd like but this is the example with which we're going for the purposes of this article.

Saving the Post Data

Finally, we're ready to actually do something with this data.

Now, we'll define a function that takes a response from the wp-remote-receiver.php and actually save it to the post meta data, but only if it doesn't already exist.

Specifically, here's what we'll do:

  • Use the Unique ID as the key
  • If the address exists for the Unique ID, then we'll do nothing
  • Otherwise, we'll also store the address and the page that was viewed

To that end, first let's define a function that will do exactly that. Note that it will accept a Unique ID which will correspond to the IP address we see above, as well as the site URL and the page URL.

private function save_post_data( $unique_id, $site_url, $page_url ) {
    if ( '' == get_post_meta( get_the_ID(), 'unique_id', true ) ) {
        add_post_meta( get_the_ID(), 'unique_id', $unique_id );
        add_post_meta( get_the_ID(), 'site_url', $site_url );
        add_post_meta( get_the_ID(), 'page_url', $page_url );
    } // end if

Based on the requirements listed above the function, we're only going to be saving data for this post if nothing currently exists for the given IP address.

At this point, we just need to make one minor modification to our get_post_response function. Update the conditional so that it calls into the function that we've defined above:

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 -->';
    $this->save_post_data( $unique_id, $site_url, $page_url );

And that's it!


The final plugin is available for review and for download on GitHub. It also includes documentation for each function that's included with the plugin as well as a README so that you can follow along with everything that was included here.

Note that if you're interested in the arguments that wp_remote_post accepts, review the previous article in which we covered this when talking about wp_remote_get.

Finally, this just scratches the surface of what's possible with the HTTP API. Hopefully, this series has helped provide a solid introduction to the API, and has helped pave the way for future work with the API.



一个文科IT宅男,喜欢折腾WordPress和被它折腾 ^_^



您的电子邮箱地址不会被公开。 必填项已用*标注