Heim  >  Artikel  >  Backend-Entwicklung  >  Entdecken Sie die WordPress-HTTP-API: Reale Darstellung von wp_remote_get

Entdecken Sie die WordPress-HTTP-API: Reale Darstellung von wp_remote_get

PHPz
PHPzOriginal
2023-09-01 17:37:011093Durchsuche

Im letzten Artikel dieser Serie haben wir uns die PHP-Funktionen angesehen, mit denen Remote-Anfragen gestellt werden können.

Im Einzelnen haben wir Folgendes überprüft:

  • file_get_contents
  • cURL

Wir haben auch WordPress-Funktionen besprochen wp_remote_get.

In diesem Artikel werden wir wp_remote_get in die Tat umsetzen. Diese Funktion ist Teil der HTTP-API – nutzen Sie sie tatsächlich, indem Sie damit die folgenden zwei Dinge abrufen:

  1. Unsere Anzahl an Followern auf Twitter
  2. Unsere neuesten Tweets

Der Vorteil besteht darin, dass wir keinen OAuth- oder Authentifizierungsmechanismus verwenden müssen, sondern lediglich Twitter-Antworten und die JSON-Funktionen von PHP nutzen.

In diesem Artikel werden wir also sehen, wie das geht, und dann werden wir alle Informationen wp_remote_get am Ende der Serie durchgehen, damit wir wissen, wie man es in Zukunft richtig macht.


Plugin-Verzeichnis vorbereiten

Wie bei allen Plugins müssen wir als Erstes ein Verzeichnis im Verzeichnis wp-content/plugins erstellen. Für die Zwecke dieser Demo nennen wir unser Plugin Twitter-Demo.

Daher haben wir das Plugin-Verzeichnis twitter-demo und die zugehörige Plugin-Datei twitter-demo.php benannt.

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

Als nächstes müssen wir den Header des Plugins entfernen, damit WordPress die Plugin-Datei erkennen kann, also machen wir das jetzt.


Plugin entfernen

Fügen Sie zunächst den folgenden Code in den Header Ihrer twitter-demo.php-Datei ein:

<?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
 */

Bitte beachten Sie, dass wir dieses Plugin nicht internationalisieren. Wir behandeln dieses Thema in einem anderen Artikel, der jedoch den Rahmen sprengt, den wir in diesem Artikel behandeln möchten.

An diesem Punkt sollten Sie das Plugin in Ihrem WordPress-Dashboard für installierte Plugins sehen können. Sie können es aktivieren; es wird jedoch nichts bewirken.

Zumindest noch nicht.


Plugins zum Leben erwecken

Wie bei anderen Demo-Plugins, die ich hier gepostet habe, halte ich es für wichtig, zunächst zu skizzieren, was das Plugin tun wird

, bevor Sie mit dem Codieren beginnen.

Daher können wir mit folgenden Ergebnissen rechnen:

    Am Ende jedes Beitrags zeigen wir eine kleine Benachrichtigung mit der Aufschrift: Ich habe
  • X Follower auf Twitter. Mein letzter Tweet war Y.
  • Wir achten darauf, dies nur auf einer einzelnen Beitragsseite zu tun, damit sie nicht im Hauptindex oder auf der Archivseite angezeigt wird.
Natürlich ist es etwas nervig, dies am Ende eines Beitrags zu haben, aber denken Sie daran, der Zweck dieses Plugins besteht darin, zu demonstrieren,

wie verwendet wird , wie eine Antwort von Twitter analysiert und angezeigt wird. wp_remote_get

Es ist uns eigentlich egal, wo der Inhalt angezeigt wird.

Lassen Sie uns also fortfahren und die Klasse löschen, die diese Funktionalität bereitstellt.

1. Twitter-Demokurs löschen

Bevor wir etwas unternehmen, entfernen wir die Klasse, die zum Senden von Anfragen an Twitter verwendet wird. Ich habe den gesamten Code unten zusammen mit der Dokumentation für jede Eigenschaft und Methode eingefügt.

<?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();

Bitte beachten Sie, dass wir die restlichen Methoden im Laufe der Zeit ergänzen werden und ich am Ende des Artikels auch den vollständigen Quellcode des Plugins bereitstellen werde.

Bevor wir fortfahren, möchte ich darauf hinweisen, dass wir für dieses Plugin das Singleton-Muster verwenden werden. Wir haben dieses Designmuster in einem früheren Artikel behandelt, und obwohl seine Vorteile den Rahmen dieses Artikels sprengen würden, empfehle ich Ihnen, den entsprechenden Artikel zu lesen, um sicherzustellen, dass Sie vollständig verstehen, warum wir das Plugin auf diese Weise eingerichtet haben.

p> Als nächstes werfen wir einen Blick auf die Funktionen, die wir aufgelistet haben, damit wir genau wissen, wohin wir wollen:

    Wir werden im Konstruktor eine Aktion zum Anhängen von Twitter-Informationen an einen einzelnen Beitrag hinzufügen
  • wird verwendet, um die Nachricht am Ende des Beitrags darzustellendisplay_twitter_information
  • Fordert tatsächlich die Daten von Twitter an und gibt sie zurück (oder null, wenn die Anfrage fehlschlägt) make_twitter_request
  • Gibt die Anzahl der Follower des angegebenen Benutzers zurück (gibt -1 zurück, wenn ein Problem vorliegt) get_follower_count
  • Gibt den letzten Tweet des Benutzers zurück oder eine Nachricht, wenn das Plugin fehlschlägt get_last_tweet
Ist es klar genug? Fordern wir nun Informationen von Twitter an, damit wir diese verarbeiten können.

2. Fordern Sie Daten von Twitter an

Zuerst füllen wir die

-Funktion mit dem folgenden Code. Bitte beachten Sie, dass ich es nach dem Code erklären werde: 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;

}

In der ersten Codezeile verwenden wir

, um unsere Anfrage zu stellen. Beachten Sie, dass wir den Parameter $username verwenden, um den JSON-Feed des Benutzers abzurufen. Beachten Sie, wie einfach es ist, die Anfrage mit der Funktion wp_remote_get 来发出我们的请求。请注意,我们使用 $username 参数来检索用户的 JSON feed。请注意,使用 wp_remote_get zu stellen.

Dieser Benutzername wird von einer anderen Funktion übergeben, die wir uns später ansehen werden.

接下来,请注意我们将代码包装在 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 的所有信息,以了解该方法的灵活性。之后,我们将详细查看响应数据,以便我们能够编写更复杂的请求并编写更多的防御性代码,更具防御性。

Das obige ist der detaillierte Inhalt vonEntdecken Sie die WordPress-HTTP-API: Reale Darstellung von wp_remote_get. Für weitere Informationen folgen Sie bitte anderen verwandten Artikeln auf der PHP chinesischen Website!

Stellungnahme:
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn
Vorheriger Artikel:PHP-KompilierungsfehlerNächster Artikel:PHP-Kompilierungsfehler