如何从WordPress REST API获取ACF文件字段的URL而非仅ID?
问题
刚接触WordPress,首次使用ACF插件和REST API。创建了带有自定义字段的自定义文章类型,其中包含一个文件字段。已为该文章类型启用REST API,能获取数据,但文件字段仅返回文件ID。已将该自定义字段的返回值设置为文件数组,也尝试过文件URL,但均未对REST API产生影响。请问有没有办法无需为每个该类型文章额外调用就能获取文件URL?
测试返回的JSON示例:
[ { "id":282, "date":"2022-08-10T16:52:58", "date_gmt":"2022-08-10T16:52:58", "guid":{ "rendered":"https://[domain]/?post_type=resourcelibrary_file&p=282" }, "modified":"2022-08-10T16:52:58", "modified_gmt":"2022-08-10T16:52:58", "slug":"auto-draft", "status":"publish", "type":"resourcelibrary_file", "link":"https://[domain]/resourcelibrary_file/auto-draft/", "template":"", "meta":[ ], "vl_bok_primary_cat":[ ], "vl_cat":[ ], "acf":{ "title":"PR Test", "author":"Test Person", "year":2022, "keywords":"test keyword list", "category":[ 21 ], "bok_cats":[ 22, 40 ], "file":283 }, "_links":{ "self":[ { "href":"https://[domain]/wp-json/wp/v2/resource_library_files/282" } ], "collection":[ { "href":"https://[domain]/wp-json/wp/v2/resource_library_files" } ], "about":[ { "href":"https://[domain]/wp-json/wp/v2/types/resourcelibrary_file" } ], "acf:term":[ { "embeddable":true, "taxonomy":"vl_bok_primary_cat", "href":"https://[domain]/wp-json/wp/v2/vl_bok_primary_cat/40" }, { "embeddable":true, "taxonomy":"vl_bok_primary_cat", "href":"https://[domain]/wp-json/wp/v2/vl_bok_primary_cat/22" }, { "embeddable":true, "taxonomy":"vl_cat", "href":"https://[domain]/wp-json/wp/v2/vl_cat/21" } ], "wp:attachment":[ { "href":"https://[domain]/wp-json/wp/v2/media?parent=282" } ], "wp:term":[ { "taxonomy":"vl_bok_primary_cat", "embeddable":true, "href":"https://[domain]/wp-json/wp/v2/vl_bok_primary_cat?post=282" }, { "taxonomy":"vl_cat", "embeddable":true, "href":"https://[domain]/wp-json/wp/v2/vl_cat?post=282" } ], "curies":[ { "name":"wp", "href":"https://api.w.org/{rel}", "templated":true } ] } } ]
解决方案
方法1:针对单个文件字段修改REST返回格式
ACF默认在REST API中仅返回字段原始值(如文件ID),即使你在字段设置中修改了返回格式。可以添加以下代码到主题的functions.php或自定义插件中,指定目标字段返回包含URL的完整信息:
add_filter('acf/rest_api/format_value', function($value, $post_id, $field) { // 替换为你的文件字段实际键名(可在ACF字段编辑页的「字段键」中查看) if ($field['key'] === 'field_xxxxxx') { if (is_numeric($value)) { $file = get_post($value); if ($file) { $value = array( 'id' => $file->ID, 'url' => wp_get_attachment_url($file->ID), 'title' => $file->post_title, 'mime_type' => $file->post_mime_type ); } } } return $value; }, 10, 3);
方法2:全局修改所有ACF文件字段的REST返回
如果需要所有ACF文件字段都在REST API中返回完整数组格式,可使用以下代码:
add_filter('acf/rest_api/field_settings', function($settings, $field) { if ($field['type'] === 'file') { // 强制REST API返回文件数组格式 $settings['return_format'] = 'array'; } return $settings; }, 10, 2);
方法3:利用REST API的嵌入式请求
无需修改代码的情况下,可在请求URL末尾添加?_embed参数,比如:
https://[domain]/wp-json/wp/v2/resource_library_files?_embed
此时响应会自动嵌入关联的媒体文件数据,你可以在_embedded['wp:attachment']中找到对应文件的URL等信息,通过匹配file字段的ID即可获取,无需额外发起请求。
内容的提问来源于stack exchange,提问作者user3562286
相关产品推荐
相关产品推荐

