You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在WordPress中通过文章标题获取记录

WordPress REST API 通过文章标题获取自定义类型记录

WordPress的REST API默认不支持直接通过标题作为路径参数查询记录,但可以通过查询参数实现,以下是两种可行方案:


方案1:使用search参数(模糊匹配,无需额外配置)

该参数会模糊搜索标题、内容等字段,返回包含目标关键词的所有team类型记录,适合不需要严格精确匹配的场景。

修改后的axios请求代码:

var axios = require('axios');

// 要搜索的标题
const targetTitle = 'John Doe';
// 对标题进行URL编码,处理空格/特殊字符
const encodedTitle = encodeURIComponent(targetTitle);

var config = {
  method: 'get',
  url: `URL/wp-json/wp/v2/team?search=${encodedTitle}`,
  headers: { 
    'Authorization': 'Basic auth', 
    'Content-Type': 'application/json'
  }
};

axios(config)
.then(function (response) {
  console.log(JSON.stringify(response.data));
})
.catch(function (error) {
  console.log(error);
});

方案2:使用filter[title]参数(精确匹配,需提前配置)

如果需要严格精确匹配标题,需先在WordPress主题的functions.php文件中添加以下代码,开启team自定义类型的filter参数支持:

add_filter( 'rest_team_collection_params', function( $params ) {
    $params['filter'] = array(
        'description'       => '通过WP_Query参数过滤结果',
        'type'              => 'object',
        'default'           => array(),
    );
    return $params;
} );

配置完成后,修改axios请求代码:

var axios = require('axios');

const targetTitle = 'John Doe';
const encodedTitle = encodeURIComponent(targetTitle);

var config = {
  method: 'get',
  url: `URL/wp-json/wp/v2/team?filter[title]=${encodedTitle}`,
  headers: { 
    'Authorization': 'Basic auth', 
    'Content-Type': 'application/json'
  }
};

axios(config)
.then(function (response) {
  console.log(JSON.stringify(response.data));
})
.catch(function (error) {
  console.log(error);
});

注意事项

  • GET请求无需携带data参数,原代码中的data字段可以直接删除,因为GET请求不会发送请求体内容。
  • 标题包含空格或特殊字符时,必须进行URL编码,避免请求报错。

内容的提问来源于stack exchange,提问作者Major

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.21 14:09:21