首頁  >  文章  >  後端開發  >  探索 WordPress HTTP API:wp_remote_get 的真實插圖

探索 WordPress HTTP API:wp_remote_get 的真實插圖

PHPz
PHPz原創
2023-09-01 17:37:011093瀏覽

在本系列的最後一篇文章中,我們了解了可用於發出遠端請求的 PHP 函數。

具體來說,我們審查了:

  • file_get_contents
  • cURL

#我們也討論了 WordPress 函數 wp_remote_get

在本文中,我們將讓 wp_remote_get 發揮作用。此函數是 HTTP API 的一部分 - 透過使用它來檢索以下兩件事來實際使用:

  1. 我們在 Twitter 上的追蹤者數量
  2. 我們最新的推文

好處是我們不需要使用任何 OAuth 或身分驗證機制,而只需要利用 Twitter 回應和 PHP 的 JSON 功能。

因此,在本文中,我們將實際了解如何做到這一點,然後我們將在本系列結束時回顧wp_remote_get 返回的所有信息,以便我們知道如何正確執行此操作在以後的工作中處理好。


準備外掛目錄

與所有外掛程式一樣,我們需要做的第一件事是在 wp-content/plugins 目錄中建立一個目錄。出於本演示的目的,我們將我們的插件稱為 Twitter 演示

因此,我們將插件目錄命名為 twitter-demo 以及關聯的插件檔案 twitter-demo.php

探索 WordPress HTTP API:wp_remote_get 的真实插图

#接下來,我們需要繼續刪除外掛程式的標頭,以便 WordPress 能夠偵測到外掛程式文件,所以我們現在就這樣做。


刪除外掛程式

首先,將以下程式碼放入 twitter-demo.php 檔案的標頭中:

<?php
/* Plugin Name: Twitter Demo
 * Plugin URI:  http://example.com/twitter-demo/
 * Description: Retrieves the number of followers and latest Tweet from your Twitter account.
 * 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
 */

請注意,我們不會將該外掛國際化。我們在另一篇文章中討論了這個主題,這超出了我們在本文中嘗試的範圍。

此時,您應該可以在 WordPress 安裝的外掛儀表板中看到該外掛程式。您可以啟動它;然而,它實際上不會做任何事情。

至少現在還沒有。


讓外掛程式栩栩如生

與我在這裡發布的其他演示插件一樣,我認為在開始編碼之前首先概述插件要做什麼非常重要。

因此,我們可以期待以下結果:

  • 在每篇文章的底部,我們都會顯示一則小通知,內容如下:我在 Twitter 上有 X 數量的追蹤者。我的上一則推文是Y
  • 我們將確保僅在單一貼文頁面上執行此操作,以便它不會顯示在主索引或存檔頁面上。

當然,在帖子底部顯示此內容有點令人討厭,但請記住,此外掛程式的目的是演示如何使用wp_remote_get,如何解析來自Twitter 的回應,以及如何顯示它。

我們不太在乎內容顯示在哪裡。

那麼,讓我們繼續刪除將提供此功能的類別。

1。刪除 Twitter 演示類別

在進行任何操作之前,我們先刪除將用於向 Twitter 發出請求的類別。我已包含以下所有程式碼以及每個屬性和方法的文檔。

<?php
/**
 * Plugin Name: Twitter Demo
 * Plugin URI:  http://tommcfarlin.com/twitter-demo/
 * Description: Retrieves the number of followers and latest Tweet from your Twitter account.
 * 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
 */

class Twitter_Demo {

	/**
	 * Instance of this class.
	 *
	 * @var      Twitter_Demo
	 */
	private static $instance;

	/**
	 * Initializes the plugin so that the Twitter information is appended to the end of a single post.
	 * Note that this constructor relies on the Singleton Pattern
	 *
	 * @access private
	 */
	private function __construct() {

	} // end constructor

	/**
	 * Creates an instance of this class
	 *
	 * @access public
	 * @return Twitter_Demo    An instance of this class
	 */
	public function get_instance() {

	} // end get_instance

	/**
	 * Appends a message to the bottom of a single post including the number of followers and the last Tweet.
	 *
	 * @access public
	 * @param  $content    The post content
	 * @return $content    The post content with the Twitter information appended to it.
	 */
	public function display_twitter_information( $content ) {

	} // end display_twitter_information

	/**
	 * Attempts to request the specified user's JSON feed from Twitter
	 *
	 * @access public
	 * @param  $username   The username for the JSON feed we're attempting to retrieve
	 * @return $json       The user's JSON feed or null of the request failed
	 */
	private function make_twitter_request( $username ) {

	} // end make_twitter_request

	/**
	 * Retrieves the number of followers from the JSON feed
	 *
	 * @access private
	 * @param  $json     The user's JSON feed
	 * @return           The number of followers for the user. -1 if the JSON data isn't properly set.
	 */
	private function get_follower_count( $json ) {

	} // end get_follower_count

	/**
	 * Retrieves the last tweet from the user's JSON feed
	 *
	 * @access private
	 * @param  $json     The user's JSON feed
	 * @return           The last tweet from the user's feed. '[ No tweet found. ]' if the data isn't properly set.
	 */
	private function get_last_tweet( $json ) {

	} // end get_last_tweet

} // end class

// Trigger the plugin
Twitter_Demo::get_instance();

請注意,我們將隨時填充這些方法的其餘部分,並且我還將在文章末尾提供該插件的完整原始程式碼。

在我們進一步討論之前,我想指出我們將為此插件使用單例模式。我們在上一篇文章中介紹了這種設計模式,儘管它的優點超出了本文的範圍,但我建議您閱讀相關文章,以確保您完全理解我們為什麼要以這種方式設定插件。 p>

接下來,讓我們來看看我們已經列出的功能,以便我們準確地知道我們的前進方向:

  • 我們將在建構函式中新增一個操作,用於將 Twitter 資訊附加到單一貼文
  • display_twitter_information 將用於在貼文底部呈現訊息
  • make_twitter_request 會實際從 Twitter 請求並傳回資料(如果請求失敗則傳回 null)
  • get_follower_count 將傳回指定使用者的追蹤者數量(如果有問題則傳回 -1)
  • get_last_tweet 將傳回使用者的最後一則推文,或如果外掛失敗則傳回一則訊息

夠清楚了嗎?現在,讓我們從 Twitter 請求訊息,以便我們可以處理它。

2。從 Twitter 請求資料

首先,讓我們使用以下程式碼填充 make_twitter_request 函數。請注意,我將在程式碼後面對其進行解釋:

private function make_twitter_request( $username ) {

	$response = wp_remote_get( 'https://twitter.com/users/' . $username . '.json' );
	try {

		// Note that we decode the body's response since it's the actual JSON feed
		$json = json_decode( $response['body'] );

	} catch ( Exception $ex ) {
		$json = null;
	} // end try/catch

	return $json;

}

在程式碼的第一行中,我們利用 wp_remote_get 來發出我們的請求。請注意,我們使用 $username 參數來檢索使用者的 JSON feed。請注意,使用 wp_remote_get 函數發出請求是多麼簡單。

此使用者名稱是從我們稍後會查看的另一個函數傳入的。

接下来,请注意我们将代码包装在 try/catch 中。这是因为向 Twitter 发出的请求可能会失败。如果没有失败,那么我们将使用 PHP 的 json_decode 函数来解码响应的正文;否则,我们会将响应设置为 null

这将使调用函数中的条件变得简单。

在我们进一步讨论之前,重要的是要注意这里有一个微妙的要点:请注意,我们正在解码返回的 $response 数组的 'body' 键。对于对此更好奇的人,我们将在下一篇文章中详细查看使用 wp_remote_get 时出现的响应。

现在,只需注意 $response 数组的 body 索引只是我们可用的一条信息。

3。调用请求函数

现在我们已经定义了负责向 Twitter 发出请求的函数,接下来让我们定义一个函数,该函数将从 Twitter 请求数据,然后将其显示在帖子内容下方。

同样,这是代码,之后我将准确解释它的作用:

public function display_twitter_information( $content ) {

	// If we're on a single post or page...
	if ( is_single() ) {

		// ...attempt to make a response to twitter. Note that you should replace your username here!
		if ( null == ( $json_response = $this->make_twitter_request( 'wptuts' ) ) ) {

			// ...display a message that the request failed
			$html = '
<div id="twitter-demo-content">';
 $html .= 'There was a problem communicating with the Twitter API..';
 $html .= '</div>
<!-- /#twitter-demo-content -->';

		// ...otherwise, read the information provided by Twitter
		} else {

			$html = '
<div id="twitter-demo-content">';
 $html .= 'I have ' . $this->get_follower_count( $json_response ) . ' followers and my last tweet was "' . $this->get_last_tweet( $json_response ) . '".';
 $html .= '</div>
<!-- /#twitter-demo-content -->';

		} // end if/else

		$content .= $html;

	} // end if/else

	return $content;

}

首先,要知道这是整个插件中最长的函数。如果您能对此进行筛选,那么您就可以开始了。

记住:这个函数将在插件完全完成后在我们的构造函数中定义的 the_content 操作期间被调用。

因此,该函数首先检查我们是否在单个帖子上。如果没有,那么它只会返回内容;否则,它将执行以下操作:

  • 尝试向 Twitter 提出请求
  • 如果请求失败,则会显示一条消息
  • 否则,如果将打印一条消息,显示关注者数量以及该人留下的最后一条推文
  • 它将把消息附加到帖子内容

重要说明:在此函数中,您可以指定要检索其信息的用户名。例如,请注意,我正在尝试通过调用 $this->make_twitter_request('wptuts') 来检索 @WPTuts 的信息。

4。阅读信息

此时,我们已准备好读取信息并将字符串连接到消息中以显示给用户。我们将使用 get_follower_count 方法和 get_last_tweet 来完成此操作。

因为这些方法非常相似,所以我们将看一下它们,然后我将在代码后面解释它们:

private function get_follower_count( $json ) {
	return ( -1 < $json->followers_count ) ? $json->followers_count : -1;
} // end get_follower_count

private function get_last_tweet( $json ) {
	return ( 0 < strlen( $json->status->text ) ) ? $json->status->text : '[ No tweet found. ]';
} // end get_last_tweet

请注意,这两个函数的相似之处在于它们都接受插件早期的 $json 数据。接下来,它们都使用三元运算符来确定是否应该返回请求的文本或默认消息。

换句话说,如果我们要显示 followers_count 并且该值大于 -1,那么我们知道我们有一个要显示的值,因此我们将返回它;否则,我们将返回 -1 作为该值未正确设置的指示符。

这使我们能够针对处理数据时可能出错的问题进行防御性编码。


Twitter 演示插件

正如所承诺的,这里是完整的源代码以及匹配的文档:

<?php
/**
 * Plugin Name: Twitter Demo
 * Plugin URI:  http://example.com/twitter-demo/
 * Description: Retrieves the number of followers and latest Tweet from your Twitter account.
 * 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
 */
class Twitter_Demo {
	/**
	 * Instance of this class.
	 *
	 * @var      Twitter_Demo
	 */
	private static $instance;

	/**
	 * Initializes the plugin so that the Twitter information is appended to the end of a single post.
	 * Note that this constructor relies on the Singleton Pattern
	 *
	 * @access private
	 */
	private function __construct() {
		add_action( 'the_content', array( $this, 'display_twitter_information' ) );
	} // end constructor

	/**
	 * Creates an instance of this class
	 *
	 * @access public
	 * @return Twitter_Demo    An instance of this class
	 */
	public function get_instance() {
		if ( null == self::$instance ) {
			self::$instance = new self;
		}
		return self::$instance;
	} // end get_instance

	/**
	 * Appends a message to the bottom of a single post including the number of followers and the last Tweet.
	 *
	 * @access public
	 * @param  $content    The post content
	 * @return $content    The post content with the Twitter information appended to it.
	 */
	public function display_twitter_information( $content ) {
		// If we're on a single post or page...
		if ( is_single() ) {
			// ...attempt to make a response to twitter. Note that you should replace your username here!
			if ( null == ( $json_response = $this--->make_twitter_request('wptuts') ) ) {

				// ...display a message that the request failed
				$html = '
<div id="twitter-demo-content">';
 $html .= 'There was a problem communicating with the Twitter API..';
 $html .= '</div>
<!-- /#twitter-demo-content -->';

				// ...otherwise, read the information provided by Twitter
			} else {

				$html = '
<div id="twitter-demo-content">';
 $html .= 'I have ' . $this->get_follower_count( $json_response ) . ' followers and my last tweet was "' . $this->get_last_tweet( $json_response ) . '".';
 $html .= '</div>
<!-- /#twitter-demo-content -->';

			} // end if/else

			$content .= $html;

		} // end if/else

		return $content;

	} // end display_twitter_information

	/**
	 * Attempts to request the specified user's JSON feed from Twitter
	 *
	 * @access public
	 * @param  $username   The username for the JSON feed we're attempting to retrieve
	 * @return $json       The user's JSON feed or null of the request failed
	 */
	private function make_twitter_request( $username ) {

		$response = wp_remote_get( 'https://twitter.com/users/' . $username . '.json' );
		try {

			// Note that we decode the body's response since it's the actual JSON feed
			$json = json_decode( $response['body'] );

		} catch ( Exception $ex ) {
			$json = null;
		} // end try/catch

		return $json;

	} // end make_twitter_request

	/**
	 * Retrieves the number of followers from the JSON feed
	 *
	 * @access private
	 * @param  $json     The user's JSON feed
	 * @return           The number of followers for the user. -1 if the JSON data isn't properly set.
	 */
	private function get_follower_count( $json ) {
		return ( -1 < $json->followers_count ) ? $json->followers_count : -1;
	} // end get_follower_count

	/**
	 * Retrieves the last tweet from the user's JSON feed
	 *
	 * @access private
	 * @param  $json     The user's JSON feed
	 * @return           The last tweet from the user's feed. '[ No tweet found. ]' if the data isn't properly set.
	 */
	private function get_last_tweet( $json ) {
		return ( 0 < strlen( $json->status->text ) ) ? $json->status->text : '[ No tweet found. ]';
	} // end get_last_tweet

} // end class

// Trigger the plugin
Twitter_Demo::get_instance();

其实很简单,对吧?事实上,代码注释的数量与实际代码行的数量一样多,因此插件本身非常小。


结论

这个演示展示了使用 wp_remote_get 与第三方服务交互、解析它们的响应并将其集成到插件中是多么容易。诚然,这非常很简单,但它仍然证明了这个概念。

在本系列的下一篇文章中,我们将查看可以传递给 wp_remote_get 的所有信息,以了解该方法的灵活性。之后,我们将详细查看响应数据,以便我们能够编写更复杂的请求并编写更多的防御性代码,更具防御性。

以上是探索 WordPress HTTP API:wp_remote_get 的真實插圖的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
上一篇:PHP 編譯錯誤下一篇:PHP 編譯錯誤