Explorez l'API HTTP WordPress : illustration réelle de wp_remote_get

PHPz
Libérer: 2023-09-01 17:38:01
original
1093 Les gens l'ont consulté

Dans le dernier article de cette série, nous avons examiné les fonctions PHP pouvant être utilisées pour effectuer des requêtes à distance.

Plus précisément, nous avons examiné :

  • file_get_contents
  • cURL

Nous avons également discuté des fonctions WordPress wp_remote_get.

Dans cet article, nous mettrons wp_remote_get à l’œuvre. Cette fonction fait partie de l'API HTTP - utilisez-la en fait pour récupérer les deux choses suivantes :

  1. Notre nombre de followers sur Twitter
  2. Nos derniers tweets

L'avantage est que nous n'avons pas besoin d'utiliser de mécanismes OAuth ou d'authentification, mais simplement d'exploiter les réponses Twitter et les capacités JSON de PHP.

Donc, dans cet article, nous allons voir comment faire cela, puis nous passerons en revue toutes les informations wp_remote_get renvoyées à la fin de la série afin que nous sachions comment le faire correctement à l'avenir.


Préparer le répertoire des plugins

Comme pour tous les plugins, la première chose que nous devons faire est de créer un répertoire dans le répertoire wp-content/plugins. Pour les besoins de cette démo, nous appellerons notre plugin Twitter Demo.

Par conséquent, nous avons nommé le répertoire du plugin twitter-demo et le fichier du plugin associé twitter-demo.php.

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

Ensuite, nous devons supprimer l’en-tête du plugin afin que WordPress puisse détecter le fichier du plugin, nous allons donc le faire maintenant.


Supprimer le plugin

Tout d'abord, mettez le code suivant dans l'en-tête de votre fichier 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
 */
Copier après la connexion

Veuillez noter que nous n'internationalisons pas ce plugin. Nous abordons ce sujet dans un autre article, qui dépasse le cadre de ce que nous essayons de faire dans cet article.

À ce stade, vous devriez pouvoir voir le plugin dans votre tableau de bord des plugins installés WordPress. Vous pouvez l'activer cependant, cela ne fera rien.

Du moins pas encore.


Donnez vie aux plugins

Comme pour les autres plugins de démonstration que j'ai publiés ici, je pense qu'il est important de d'abord décrire ce que le plugin va faire

avant de commencer à coder.

Nous pouvons donc nous attendre aux résultats suivants :

    Au bas de chaque message, nous affichons une petite notification indiquant : J'ai
  • X abonnés sur Twitter. Mon dernier tweet était Y.
  • Nous veillerons à ne faire cela que sur une seule page de publication afin qu'elle n'apparaisse pas sur la page d'index principale ou d'archive.
Bien sûr, c'est un peu ennuyeux d'avoir ceci en bas d'un message, mais rappelez-vous, le but de ce plugin est de démontrer

comment est utilisé , comment analyser une réponse de Twitter et comment l'afficher. wp_remote_get

Nous ne nous soucions pas vraiment de l'endroit où le contenu est affiché.

Alors, allons-y et supprimons la classe qui fournira cette fonctionnalité.

1. Supprimer le cours de démonstration Twitter

Avant de faire quoi que ce soit, supprimons la classe qui sera utilisée pour faire des requêtes à Twitter. J'ai inclus tout le code ci-dessous ainsi que la documentation pour chaque propriété et méthode.

<?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();
Copier après la connexion

Veuillez noter que nous compléterons le reste de ces méthodes au fur et à mesure, et je fournirai également le code source complet du plugin en fin d'article.

Avant d'aller plus loin, je tiens à souligner que nous utiliserons le modèle singleton pour ce plugin. Nous avons couvert ce modèle de conception dans un article précédent, et bien que ses avantages dépassent la portée de cet article, je vous recommande de lire l'article associé pour vous assurer de bien comprendre pourquoi nous avons configuré le plugin de cette façon.

Ensuite, jetons un coup d'œil aux fonctionnalités que nous avons répertoriées pour savoir exactement où nous allons :

    Nous ajouterons une action dans le constructeur pour ajouter des informations Twitter à une seule publication
  • sera utilisé pour afficher le message en bas du postdisplay_twitter_information
  • Demandera et renverra réellement les données de Twitter (ou null si la demande échoue) make_twitter_request
  • Renvoie le nombre de followers de l'utilisateur spécifié (renvoie -1 en cas de problème) get_follower_count
  • Renverra le dernier tweet de l'utilisateur, ou un message si le plugin échoue get_last_tweet
Est-ce assez clair ? Maintenant, demandons des informations à Twitter afin que nous puissions les traiter.

2. Demander des données à Twitter

Tout d’abord, remplissons la fonction

avec le code suivant. Attention, je l'expliquerai après le code : 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;

}
Copier après la connexion

Dans la première ligne de code, nous utilisons

pour faire notre requête. Notez que nous utilisons le paramètre $username pour récupérer le flux JSON de l'utilisateur. Remarquez à quel point il est simple de faire la demande en utilisant la fonction wp_remote_get 来发出我们的请求。请注意,我们使用 $username 参数来检索用户的 JSON feed。请注意,使用 wp_remote_get.

Ce nom d'utilisateur est transmis à partir d'une autre fonction que nous examinerons plus tard.

接下来,请注意我们将代码包装在 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;

}
Copier après la connexion

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

记住:这个函数将在插件完全完成后在我们的构造函数中定义的 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
Copier après la connexion

请注意,这两个函数的相似之处在于它们都接受插件早期的 $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();
Copier après la connexion

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


结论

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

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

Ce qui précède est le contenu détaillé de. pour plus d'informations, suivez d'autres articles connexes sur le site Web de PHP en chinois!

source:php.cn
Déclaration de ce site Web
Le contenu de cet article est volontairement contribué par les internautes et les droits d'auteur appartiennent à l'auteur original. Ce site n'assume aucune responsabilité légale correspondante. Si vous trouvez un contenu suspecté de plagiat ou de contrefaçon, veuillez contacter admin@php.cn
Tutoriels populaires
Plus>
Derniers téléchargements
Plus>
effets Web
Code source du site Web
Matériel du site Web
Modèle frontal
À propos de nous Clause de non-responsabilité Sitemap
Site Web PHP chinois:Formation PHP en ligne sur le bien-être public,Aidez les apprenants PHP à grandir rapidement!