性价比最高的香港ASP、PHP主机提供商
做网站,就上凡科建站

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

Loading
0
Comodo SLL证书促销 - 免费ssl证书申请_ssl证书购买_ev ssl证书_https证书购买 - GDCA_数安时代

在前面的文章中,我们创建了一个小插件作为 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:

2016-06-19_110030_wpdaxue_com

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

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;

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 :).

2016-06-19_110202_wpdaxue_com

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

2016-06-19_110243_wpdaxue_com

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

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

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

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

2016-06-19_110415_wpdaxue_com

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
 
}

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 );
 
}

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 指南:回顾
支付宝扫码打赏 微信打赏

如果文章对你有帮助,欢迎点击上方按钮打赏作者

MetInfo | 最适合企业网站建设的cms系统

关于 倡萌

一个疯狂的 WordPress 爱好者,喜欢折腾 WordPress 主题,分享 WordPress 资源。如果你也喜欢 WordPress,欢迎和我一起交流!

精彩推荐

为你的WordPress主题框架开发插件

为你的WordPress主题框架开发插件

使用wp_editor函数快速集成TinyMCE编辑器

使用wp_editor函数快速集成TinyMCE编辑器

发表评论