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

麻雀的确可爱,它的脑袋很小,只有栗子那么大,眼晴虽小却非常有神,它的身体小巧成蛋状流线型,放在手上只占手掌的一半。它浑身长着灰褐色羽毛,和树皮色相似,是一种保护色,它颈部和腹部的毛发白,显得很匀称,它的尾巴像半张开的小扇子。它飞得很快,也很有趣,那么一窜窜的。
本文是《WordPress HTTP API 指南》专题的第 7 篇,共 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 指南:回顾

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

当然,通过实例可以看到如何使用函数发出请求,甚至如何设置一个脚本来负责接收数据并返回数据,但它是没有多大用处,除非我们对它进行改进。在本系列的最后一篇文章,我们会重新审视上一篇文章所创建的插件,并对它进行改进。

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

以下为原文:http://code.tutsplus.com/tutorials/a-look-at-the-wordpress-http-api-saving-data-from-wp_remote_post--wp-32505

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:

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

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:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
<?php

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

<?php // 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:

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

#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:

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

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

Then, add the following function to your class:

1
2
3
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

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.

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

}

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:

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

}

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!

Conclusion

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.

以上就是WordPress HTTP API 指南:从 wp_remote_post 保存数据。学习是为了自己的将来,努力拼搏、奋斗吧!更多关于WordPress HTTP API 指南:从 wp_remote_post 保存数据请关注haodaima.com其它相关文章!

您可能有感兴趣的文章
WordPress出现“下载失败。 用户阻止了HTTP请求。”错误怎么办?

WordPress HTTP API 指南:回顾

WordPress HTTP API 指南:wp_remote_post 实例

WordPress HTTP API 指南:wp_remote_get 参数

WordPress HTTP API 指南:wp_remote_get 概述