WordPress HTTP API を探索する: wp_remote_get の実例

PHPz
リリース: 2023-09-01 17:38:01
オリジナル
1090 人が閲覧しました

このシリーズの前回の記事では、リモート リクエストを行うために使用できる PHP 関数について説明しました。

具体的にレビューした内容:

  • file_get_contents
  • ######カール######
  • WordPress 関数 wp_remote_get
  • についても説明しました。

この記事では、wp_remote_get を機能させます。この関数は HTTP API の一部です。実際にこの関数を使用して、次の 2 つを取得します。

Twitterのフォロワー数 私たちの最新のツイート

  1. 利点は、OAuth や認証メカニズムを使用する必要がなく、Twitter の応答と PHP の JSON 機能だけを利用できることです。
  2. したがって、この記事では、実際にその方法を確認し、その後、このシリーズの最後に
  3. wp_remote_get
が返すすべての情報を確認して、正しく実行する方法を確認します。将来 仕事ではうまく対処してください。

プラグインディレクトリの準備 すべてのプラグインと同様に、最初に行う必要があるのは、

wp-content/plugins
ディレクトリ内にディレクトリを作成することです。このデモでは、プラグインを

TwitterDemo

と呼びます。

したがって、プラグイン ディレクトリに twitter-demo 、関連するプラグイン ファイルに twitter-demo.php

という名前を付けました。

次に、WordPress がプラグイン ファイルを検出できるように、プラグインのヘッダーを削除する必要があるため、ここでそれを行います。

探索 WordPress HTTP API:wp_remote_get 的真实插图プラグインの削除

まず、

twitter-demo.php
ファイルのヘッダーに次のコードを挿入します。 リーリー

このプラグインは

国際化されないことに注意してください。このトピックについては別の記事で説明しますが、この記事で行う内容の範囲を超えています。

この時点で、WordPress にインストールされているプラ​​グイン ダッシュボードにプラグインが表示されるはずです。アクティブ化することはできますが、実際には何も行われません。

少なくともまだです。

プラグインを実現する

ここに投稿した他のデモ プラグインと同様に、コーディングを開始する前に、まずプラグインが何を行うかについて概要を説明することが重要だと思います。

したがって、次の結果が期待できます:


各投稿の下部に、次のような小さな通知が表示されます: Twitter には #xxx

人のフォロワーがいます。私の最後のツイートは

Y でした。

これはメインのインデックスやアーカイブ ページには表示されないように、単一の投稿ページでのみ実行するようにします。

  • もちろん、これを投稿の最後に置くのは少し面倒ですが、このプラグインの目的は、wp_remote_get を使用して Twitter からの応答を どのように 解析するかをデモンストレーションすることであることを覚えておいてください。 とその表示方法。
  • コンテンツがどこに表示されるかはあまり気にしません。
それでは、この機能を提供するクラスを削除しましょう。

###1。 Twitter デモ クラスを削除します 何かを行う前に、Twitter にリクエストを行うために使用されるクラスを削除しましょう。以下のすべてのコードと、各プロパティとメソッドのドキュメントを含めました。 リーリー これらのメソッドの残りの部分は順次埋めていきます。記事の最後にはプラグインの完全なソース コードも提供します。

先に進む前に、このプラグインにはシングルトン パターンを使用することを指摘しておきます。この設計パターンについては以前の記事で説明しましたが、その利点についてはこの記事の範囲を超えていますが、プラグインをこのように設定した理由を十分に理解するために、関連記事を読むことをお勧めします。

次に、私たちがどこに向かっているのかを正確に知るために、リストした機能を見てみましょう:

Twitter 情報を 1 つの投稿に追加するためのアクションをコンストラクターに追加します

display_twitter_information

は、投稿の下部にメッセージを表示するために使用されます

p>

make_twitter_request

実際に Twitter からデータをリクエストして返します (リクエストが失敗した場合は null を返します)
  • get_follower_count
  • 指定したユーザーのフォロワー数を返します (問題がある場合は -1 を返します)
  • get_last_tweet
  • ユーザーの最後のツイート、またはプラグインが失敗した場合はメッセージを返します
  • それは十分に明確ですか?次に、情報を処理できるように Twitter に情報をリクエストしてみましょう。
  • ###2。 Twitter からのデータのリクエスト まず、
  • make_twitter_request
  • 関数に次のコードを入力しましょう。コードの後に​​説明します: リーリー コードの最初の行では、
  • wp_remote_get
を使用してリクエストを行っています。ユーザーの JSON フィードを取得するには、

$username

パラメーターを使用することに注意してください。

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 中国語 Web サイトの他の関連記事を参照してください。

ソース:php.cn
このウェブサイトの声明
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。
人気のチュートリアル
詳細>
最新のダウンロード
詳細>
ウェブエフェクト
公式サイト
サイト素材
フロントエンドテンプレート
私たちについて 免責事項 Sitemap
PHP中国語ウェブサイト:福祉オンライン PHP トレーニング,PHP 学習者の迅速な成長を支援します!