【问题标题】:How to return the permalink in WordPress REST API with ACF?如何使用 ACF 返回 WordPress REST API 中的永久链接?
【发布时间】:2019-09-19 10:49:40
【问题描述】:

我正在使用 ACF + ACF to REST API 插件。

我有一个全局选项页面,其中包含一个链接到帖子的字段(这是一个 ACF 帖子关系字段)。

如果我导航到:/wp-json/acf/v3/options/options

响应如下所示:

{
  "acf": {
    "sticker_button": {
      "title": "Come & visit",
      "post_object": {
        "ID": 311,
        "post_author": "2",
        "post_date": "2019-04-30 18:39:50",
        "post_date_gmt": "2019-04-30 17:39:50",
        "post_content": "",
        "post_title": "test",
        "post_excerpt": "",
        "post_status": "publish",
        "comment_status": "closed",
        "ping_status": "closed",
        "post_password": "",
        "post_name": "test",
        "to_ping": "",
        "pinged": "",
        "post_modified": "2019-04-30 18:39:50",
        "post_modified_gmt": "2019-04-30 17:39:50",
        "post_content_filtered": "",
        "post_parent": 97,
        "guid": "https://example.dev.env.example.com/?page_id=311",
        "menu_order": 0,
        "post_type": "page",
        "post_mime_type": "",
        "comment_count": "0",
        "filter": "raw"
      }
    }
  }
}

因为我正在使用 SPA 来使用这些数据,所以我不想发出另一个 API 请求只是为了获取此帖子的永久链接/链接。

有没有办法在上述帖子的回复中显示永久链接以及post_object

仅仅使用post_name 手动建立链接是不够的,因为它可能是另一个的子页面。我在运行时需要实际的永久链接,post_name 不受页面层次结构的影响。

非常感谢您的帮助。

【问题讨论】:

    标签: php json wordpress api advanced-custom-fields


    【解决方案1】:

    看起来 ACF to Rest 插件有一个 WP 过滤器列表,您可以利用这些过滤器来获取各种类型的 WP REST 路由响应(请参阅here)。

    我的建议是使用acf/rest_api/{type}/prepare_item 过滤器,如果您想更改单个响应项的响应或acf/rest_api/{type}/get_fields 过滤器适用于typeoption 的所有对象 - 根据 REST 路由在你的问题中。

    这是使用acf/rest_api/{type}/get_fields 的示例代码(找到here):

    function options_fields_filter( $data, $request ) {
       // here's where you'd mutate `$data` 
    
       return $data;
    }
    
    add_filter( 'acf/rest_api/option/get_fields', 'option_fields_filter', 10, 2 );
    

    希望这会有所帮助。如果您想针对其他“类型”(例如特定帖子类型)利用更多指定过滤器,请深入了解位于 here 的 REST API 控制器。

    【讨论】:

    • 谢谢你...有什么方法可以知道 $data 的结构是什么样的,而无需先将其注销?我现在工作有点盲目。每个更改都需要几分钟的部署(由于我们的设置方式)。
    • @MichaelGiovanniPumo 我认为如果不进行进一步的本地测试和调试,您无法知道通过过滤器发送的内容的结构。
    【解决方案2】:

    我无法让过滤器工作。 但是,使用 ?p= 参数和 post.ID 您可以重定向到帖子。

    我最终以这种方式解决了链接的问题:

    // JSX/React
    <a href={`/?p=${ post.ID }`}>
       { post.post_title }
    </a>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-10-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-10-30
      相关资源
      最近更新 更多