Rumah  >  Artikel  >  pembangunan bahagian belakang  >  Terokai API HTTP WordPress: Ilustrasi kehidupan sebenar wp_remote_get

Terokai API HTTP WordPress: Ilustrasi kehidupan sebenar wp_remote_get

PHPz
PHPzasal
2023-09-01 17:37:011093semak imbas

Dalam artikel terakhir siri ini, kami melihat fungsi PHP yang boleh digunakan untuk membuat permintaan jauh.

Secara khusus, kami menyemak:

  • fail_dapatkan_kandungan
  • 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_getcURL

Kami juga membincangkan fungsi WordPress wp_remote_get.

Dalam artikel ini, kami akan meletakkan wp_remote_get untuk berfungsi. Fungsi ini adalah sebahagian daripada API HTTP - sebenarnya gunakannya dengan menggunakannya untuk mendapatkan semula dua perkara berikut: 🎜
    🎜Bilangan pengikut kami di Twitter 🎜Tweet terbaru kami
🎜Faedahnya ialah kami tidak perlu menggunakan sebarang mekanisme OAuth atau pengesahan, tetapi hanya memanfaatkan respons Twitter dan keupayaan JSON PHP. 🎜 🎜Jadi dalam artikel ini kita sebenarnya akan melihat bagaimana untuk melakukan ini dan kemudian kita akan menyemak semua maklumat yang dikembalikan oleh wp_remote_get pada penghujung siri ini supaya kita tahu cara melakukannya dengan betul pada masa akan datang. ia baik di tempat kerja. 🎜

Sediakan direktori pemalam

🎜Seperti semua pemalam, perkara pertama yang perlu kita lakukan ialah mencipta direktori dalam direktori wp-content/plugins. Untuk tujuan demo ini, kami akan memanggil pemalam kami Twitter Demo. 🎜 🎜Oleh itu, kami menamakan direktori pemalam twitter-demo dan fail pemalam yang berkaitan twitter-demo.php. 🎜 🎜Teroka API HTTP WordPress: ilustrasi sebenar wp_remote_get🎜 🎜Seterusnya, kami perlu meneruskan dan mengalih keluar pengepala pemalam supaya WordPress dapat mengesan fail pemalam, jadi kami akan melakukannya sekarang. 🎜

Padam pemalam

🎜Mula-mula, letakkan kod berikut ke dalam pengepala fail twitter-demo.php anda: 🎜
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;

}
🎜Sila ambil perhatian bahawa kami tidak akan mengantarabangsakan pemalam ini. Kami membincangkan topik ini dalam artikel lain, yang berada di luar skop apa yang kami cuba lakukan dalam artikel ini. 🎜 🎜Pada ketika ini, anda sepatutnya dapat melihat pemalam dalam papan pemuka pemalam yang dipasang WordPress anda. Anda boleh mengaktifkannya; walau bagaimanapun, ia tidak akan melakukan apa-apa. 🎜 🎜Sekurang-kurangnya belum lagi. 🎜

Menghidupkan pemalam

🎜Seperti pemalam demo lain yang telah saya siarkan di sini, saya fikir adalah penting untuk menggariskan terlebih dahulu perkara yang akan dilakukan oleh pemalamsebelum anda memulakan pengekodan. 🎜 🎜Oleh itu, kita boleh mengharapkan keputusan berikut: 🎜 🎜 🎜Di bahagian bawah setiap siaran, kami akan memaparkan pemberitahuan kecil yang berbunyi: Saya mempunyai X bilangan pengikut di Twitter. Tweet terakhir saya ialah Y. 🎜Kami akan memastikan anda hanya melakukan ini pada satu halaman siaran supaya ia tidak dipaparkan pada indeks utama atau halaman arkib. 🎜Sudah tentu, ia agak menjengkelkan untuk mempunyai ini di bahagian bawah siaran, tetapi ingat, tujuan pemalam ini adalah untuk menunjukkan cara menghuraikan respons daripada Twitter menggunakan wp_remote_get, dan cara untuk memaparkannya. 🎜 🎜Kami tidak begitu kisah di mana kandungan dipaparkan. 🎜 🎜Jadi, mari teruskan dan padamkan kelas yang akan menyediakan fungsi ini. 🎜

1. Alih keluar kelas demo Twitter

🎜Sebelum melakukan apa-apa, mari alih keluar kelas yang akan digunakan untuk membuat permintaan ke Twitter. Saya telah memasukkan semua kod di bawah bersama-sama dengan dokumentasi untuk setiap harta dan kaedah. 🎜
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
🎜Sila ambil perhatian bahawa kami akan mengisi selebihnya kaedah ini semasa kami pergi, dan saya juga akan memberikan kod sumber penuh pemalam di penghujung artikel. 🎜 🎜Sebelum kita pergi lebih jauh, saya ingin menunjukkan bahawa kita akan menggunakan corak tunggal untuk pemalam ini. Kami membincangkan corak reka bentuk ini dalam artikel sebelumnya, dan walaupun kelebihannya berada di luar skop artikel ini, saya mengesyorkan anda membaca artikel berkaitan untuk memastikan anda memahami sepenuhnya mengapa kami menyediakan pemalam dengan cara ini. 🎜 Seterusnya, mari lihat ciri yang telah kami senaraikan supaya kami tahu dengan tepat ke mana kami tuju: 🎜 🎜 🎜Kami akan menambah tindakan dalam pembina untuk menambahkan maklumat Twitter pada satu siaran 🎜 display_twitter_information akan digunakan untuk memaparkan mesej di bahagian bawah siaran 🎜 make_twitter_request sebenarnya akan meminta dan mengembalikan data daripada Twitter (mengembalikan batal jika permintaan gagal) 🎜 get_follower_count akan mengembalikan bilangan pengikut pengguna yang ditentukan (mengembalikan -1 jika terdapat masalah) 🎜 get_last_tweet akan mengembalikan tweet terakhir pengguna, atau mesej jika pemalam gagal 🎜Adakah ia cukup jelas? Sekarang, mari kita meminta maklumat daripada Twitter supaya kita boleh memprosesnya. 🎜

2. Minta data daripada Twitter

🎜Mula-mula, mari isikan fungsi make_twitter_request dengan kod berikut. Sila ambil perhatian bahawa saya akan menerangkannya selepas kod: 🎜
<?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();
🎜Dalam baris pertama kod, kami menggunakan wp_remote_get untuk membuat permintaan kami. Harap maklum bahawa kami menggunakan parameter $username untuk mendapatkan semula suapan JSON pengguna. Perhatikan betapa mudahnya untuk membuat permintaan menggunakan fungsi wp_remote_get. 🎜 🎜Nama pengguna ini dihantar dari fungsi lain yang akan kita lihat nanti. 🎜

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

Atas ialah kandungan terperinci Terokai API HTTP WordPress: Ilustrasi kehidupan sebenar wp_remote_get. Untuk maklumat lanjut, sila ikut artikel berkaitan lain di laman web China PHP!

Kenyataan:
Kandungan artikel ini disumbangkan secara sukarela oleh netizen, dan hak cipta adalah milik pengarang asal. Laman web ini tidak memikul tanggungjawab undang-undang yang sepadan. Jika anda menemui sebarang kandungan yang disyaki plagiarisme atau pelanggaran, sila hubungi admin@php.cn
Artikel sebelumnya:Ralat penyusunan PHPArtikel seterusnya:Ralat penyusunan PHP