🆕 Bricks 2.4 已发布:查询循环性能提升 40%,迁移教程同步更新 →

首页 / 中文教程 / 教程

Bricks 中调用 API 入门(以 Chuck Norris 语录为例)

教程:Bricks 中调用 API 入门(以 Chuck Norris 语录为例)——Bricks 附完整代码可直接复用,适合外贸独立站与 WordPress 开发者。

Ray ChanRay Chan·2026-08-12·约 5 分钟
目录
  1. 1.创建自定义函数
  2. 2.获取 API 响应
  3. 3.把 JSON 对象转成 PHP 数组
  4. 4.返回目标值

本教程通过从公共 API 拉取一条动态的 Chuck Norris 语录,带你掌握在 Bricks 中调用 API 的基础流程。

创建自定义函数

打开子主题的 functions.php,创建函数 get_random_chuck_norris_quote,先返回一段占位文本:

function get_random_chuck_norris_quote(){
   return 'This function works';
}

在 Bricks 编辑器里打开一个页面,用 Bricks 的 echo 函数把这个函数输出到目标元素里(本例用的是 Testimonial 元素):

去前端检查一下有没有生效:

函数生效了!接下来接入 API。

获取 API 响应

先把 API 地址存进变量 $random_url_api。打开 https://api.chucknorris.io/ 网站,官方给出的随机语录 API 地址是 https://api.chucknorris.io/jokes/random。

用 GET 方法发一个 HTTP 请求,把响应存进新变量 $response,这里用 wp_safe_remote_get() 函数,并 var_dump 一下看看 API 返回了什么:

function get_random_chuck_norris_quote(){
  $random_url_api = 'https://api.chucknorris.io/jokes/random';
  $response = wp_safe_remote_get($random_url_api);
  // Stop the function if the response returns an error
  if ( is_wp_error( $response ) ) {
	return false;
  }
  // Let's check the response content
  var_dump($response);
}

刷新前端页面,应该会看到下面这样的输出(一大段数组,包含 headers、body、response、cookies、http_response 等):

Array
(
    [headers] => Requests_Utility_CaseInsensitiveDictionary Object
        (
            [data:protected] => Array
                (
                    [date] => Wed, 16 Nov 2022 09:21:15 GMT
                    [content-type] => application/json;charset=UTF-8
                    [via] => 1.1 vegur
                    [cf-cache-status] => DYNAMIC
                    [report-to] => {"endpoints":[{"url":"https:\/\/a.nel.cloudflare.com\/report\/v3?s=73SiirMj%2Btof7vtFw22wSz0zX%2FIf4zi5%2F05XDrR9mADuLd3CboRtOC2jn2r%2FRvHXPly1lNPh3r8%2BTvTf9SdtuIQHtMTj4oC0CDt2bP1J7sYs%2FRLkOizhLZRB1VaNfVsGJkubEuSQWZ2OHly%2FUv86gXg%3D"}],"group":"cf-nel","max_age":604800}
                    [nel] => {"success_fraction":0,"report_to":"cf-nel","max_age":604800}
                    [server] => cloudflare
                    [cf-ray] => 76af27c9ba2759fb-MXP
                    [content-encoding] => gzip
                    [alt-svc] => h3=":443"; ma=86400, h3-29=":443"; ma=86400
                )
        )
    [body] => {"categories":[],"created_at":"2020-01-05 13:42:23.880601","icon_url":"https://assets.chucknorris.host/img/avatar/chuck-norris.png","id":"psoHkcAVSWCD1cuXGRRveg","updated_at":"2020-01-05 13:42:23.880601","url":"https://api.chucknorris.io/jokes/psoHkcAVSWCD1cuXGRRveg","value":"Chuck Norris is ALL that AND a bag of chips!"}
    [response] => Array
        (
            [code] => 200
            [message] => OK
        )
    [cookies] => Array
        (
        )
    [filename] => 
    [http_response] => WP_HTTP_Requests_Response Object
        (
            [response:protected] => Requests_Response Object
                (
                    [body] => {"categories":[],"created_at":"2020-01-05 13:42:23.880601","icon_url":"https://assets.chucknorris.host/img/avatar/chuck-norris.png","id":"psoHkcAVSWCD1cuXGRRveg","updated_at":"2020-01-05 13:42:23.880601","url":"https://api.chucknorris.io/jokes/psoHkcAVSWCD1cuXGRRveg","value":"Chuck Norris is ALL that AND a bag of chips!"}
                    [raw] => HTTP/1.1 200 OK
Date: Wed, 16 Nov 2022 09:21:15 GMT
Content-Type: application/json;charset=UTF-8
Transfer-Encoding: chunked
Connection: close
Via: 1.1 vegur
CF-Cache-Status: DYNAMIC
Report-To: {"endpoints":[{"url":"https:\/\/a.nel.cloudflare.com\/report\/v3?s=73SiirMj%2Btof7vtFw22wSz0zX%2FIf4zi5%2F05XDrR9mADuLd3CboRtOC2jn2r%2FRvHXPly1lNPh3r8%2BTvTf9SdtuIQHtMTj4oC0CDt2bP1J7sYs%2FRLkOizhLZRB1VaNfVsGJkubEuSQWZ2OHly%2FUv86gXg%3D"}],"group":"cf-nel","max_age":604800}
NEL: {"success_fraction":0,"report_to":"cf-nel","max_age":604800}
Server: cloudflare
CF-RAY: 76af27c9ba2759fb-MXP
Content-Encoding: gzip
alt-svc: h3=":443"; ma=86400, h3-29=":443"; ma=86400
{"categories":[],"created_at":"2020-01-05 13:42:23.880601","icon_url":"https://assets.chucknorris.host/img/avatar/chuck-norris.png","id":"psoHkcAVSWCD1cuXGRRveg","updated_at":"2020-01-05 13:42:23.880601","url":"https://api.chucknorris.io/jokes/psoHkcAVSWCD1cuXGRRveg","value":"Chuck Norris is ALL that AND a bag of chips!"}
                    [headers] => Requests_Response_Headers Object
                        (
                            [data:protected] => Array
                                (
                                    [date] => Array
                                        (
                                            [0] => Wed, 16 Nov 2022 09:21:15 GMT
                                        )
                                    [content-type] => Array
                                        (
                                            [0] => application/json;charset=UTF-8
                                        )
                                    [via] => Array
                                        (
                                            [0] => 1.1 vegur
                                        )
                                    [cf-cache-status] => Array
                                        (
                                            [0] => DYNAMIC
                                        )
                                    [report-to] => Array
                                        (
                                            [0] => {"endpoints":[{"url":"https:\/\/a.nel.cloudflare.com\/report\/v3?s=73SiirMj%2Btof7vtFw22wSz0zX%2FIf4zi5%2F05XDrR9mADuLd3CboRtOC2jn2r%2FRvHXPly1lNPh3r8%2BTvTf9SdtuIQHtMTj4oC0CDt2bP1J7sYs%2FRLkOizhLZRB1VaNfVsGJkubEuSQWZ2OHly%2FUv86gXg%3D"}],"group":"cf-nel","max_age":604800}
                                        )
                                    [nel] => Array
                                        (
                                            [0] => {"success_fraction":0,"report_to":"cf-nel","max_age":604800}
                                        )
                                    [server] => Array
                                        (
                                            [0] => cloudflare
                                        )
                                    [cf-ray] => Array
                                        (
                                            [0] => 76af27c9ba2759fb-MXP
                                        )
                                    [content-encoding] => Array
                                        (
                                            [0] => gzip
                                        )
                                    [alt-svc] => Array
                                        (
                                            [0] => h3=":443"; ma=86400, h3-29=":443"; ma=86400
                                        )
                                )
                        )
                    [status_code] => 200
                    [protocol_version] => 1.1
                    [success] => 1
                    [redirects] => 0
                    [url] => https://api.chucknorris.io/jokes/random
                    [history] => Array
                        (
                        )
                    [cookies] => Requests_Cookie_Jar Object
                        (
                            [cookies:protected] => Array
                                (
                                )
                        )
                )
            [filename:protected] => 
            [data] => 
            [headers] => 
            [status] => 
        )
)

可以看到它返回了一个数组,里面大部分信息我们用不上,我们只需要位于 [body] 里的语录文本。

那就只取 body 部分,用 wp_remote_retrieve_body() 函数:

function get_random_chuck_norris_quote(){
  $random_url_api = 'https://api.chucknorris.io/jokes/random';
  $response = wp_safe_remote_get($random_url_api);
  // Stop the function if the response returns an error
  if ( is_wp_error( $response ) ) {
	return false;
  }
  // Get the body part
  $response_body = wp_remote_retrieve_body( $response );
  // Let's check the response body content
  var_dump($response_body);
}

输出是一个 JSON 对象,包含 categories、id、url……以及我们真正要找的 value:

{
   "categories":[
   ],
   "created_at":"2020-01-05 13:42:26.447675",
   "icon_url":"https://assets.chucknorris.host/img/avatar/chuck-norris.png",
   "id":"wOgZCCWDReOnr3ws_Sqw2g",
   "updated_at":"2020-01-05 13:42:26.447675",
   "url":"https://api.chucknorris.io/jokes/wOgZCCWDReOnr3ws_Sqw2g",
   "value":"No matter how manly and hetro you claim to be, if you are given a nude photo of Chuck Norris, you will be dead from carpal tunnel syndrome within 4 hours."
}

把 JSON 对象转成 PHP 数组

越来越接近了!现在返回的 JSON 对象把语录文本放在 value 里。

要用 json_decode() 函数把 JSON 对象转成 PHP 数组,再提取数据。先 var_dump 看看结果:

function get_random_chuck_norris_quote(){
  $random_url_api = 'https://api.chucknorris.io/jokes/random';
  $response = wp_safe_remote_get($random_url_api);
  // Stop the function if the response returns an error
  if ( is_wp_error( $response ) ) {
	return false;
  }
  // Get the body part
  $response_body = wp_remote_retrieve_body( $response );
  // Decode the JSON object into a PHP array
  $response_body_decoded = json_decode( $response_body, true );
  // Let's check the response body content
  var_dump($response_body_decoded);
}

输出如下数组:

Array
(
    [categories] => Array
        (
        )
    [created_at] => 2020-01-05 13:42:28.984661
    [icon_url] => https://assets.chucknorris.host/img/avatar/chuck-norris.png
    [id] => nYj4tJQ-T4ioHrzbr8rFMg
    [updated_at] => 2020-01-05 13:42:28.984661
    [url] => https://api.chucknorris.io/jokes/nYj4tJQ-T4ioHrzbr8rFMg
    [value] => By the time you see Chuck Norris in your rearview mirror, he's already kicked you in the face and is 10 car lengths ahead of you.
)

相关阅读:

返回目标值

快完成了!现在从数组里取出 value,并在函数里返回它:

function get_random_chuck_norris_quote(){
  $random_url_api = 'https://api.chucknorris.io/jokes/random';
  $response = wp_safe_remote_get($random_url_api);
  // Stop the function if the response returns an error
  if ( is_wp_error( $response ) ) {
	return false;
  }
  // Get the body part 
  $response_body = wp_remote_retrieve_body( $response );
  // Decode the JSON object into a PHP array
  $response_body_decoded = json_decode( $response_body, true );
  // Return the quoted text
  return $response_body_decoded['value'];
}

搞定!我们成功用公共 API 做出了一个完全没用但动态的 Chuck Norris 语录。恭喜!

适用场景与常见误区

这种「服务端函数 + 动态标签」的套路,凡是页面要显示外部数据都能用:天气、汇率、快递状态、库存、社交媒体动态、随机语录等。新手常踩两个坑:一是每次页面加载都去打外部 API,没做缓存,流量一大就被限流甚至拖慢整站;二是把密钥写进前端代码,等于公开泄露。正确做法是把密钥留在 functions.php 的服务端函数里,用 WordPress Transients 缓存远程结果(具体缓存时长按官方文档或业务需求定),并对 wp_remote_get 的返回用 is_wp_error 兜底,失败时用静态文案降级而不是报错。

常见问题(FAQ)

Q:Bricks 里调 API 必须写 PHP 函数吗? A:是的。Bricks 的动态标签走的是服务端 PHP,所以先在子主题 functions.php 里写好取值函数,再用 {echo:函数名} 这类动态标签调用,前端只拿到最终结果。

Q:远程请求会不会拖慢页面? A:会。建议用 WordPress Transients 把结果缓存起来,避免每次访问都现打外部 API;缓存时长按官方文档或你的更新频率来定。

Q:调用失败页面会报错吗? A:教程里已经用 is_wp_error() 做了兜底返回 false。生产环境最好再加一层失败时的静态 fallback 文案,别让用户看到空白或报错。

Q:能调用需要鉴权的 API 吗? A:可以。把密钥放在服务端函数里,用 wp_safe_remote_get 带上授权 header 即可,密钥千万不要写进前端代码。

延伸阅读

Ray Chan

站长

Ray Chan

WordPress Developer & Bricks Specialist

WordPress developer with 10+ years of client builds. Switched to Bricks in 2023 — now builds fast WordPress sites and migrates legacy Elementor/Divi projects.

延伸阅读