在 WordPress 5.9 中将自定义帖子类型与 REST API 端点集成

问题描述 投票:0回答:1

我正在使用一个自定义 WordPress 网站,并尝试扩展 REST API 以包含具有关联自定义字段的自定义帖子类型。我使用的是 WordPress 5.9,并按照文档使用 'show_in_rest' => true 注册自定义帖子类型。

这是我的主题的functions.php 中的代码片段:

function create_movie_post_type() {
  register_post_type('movie',
    array(
      'labels' => array(
        'name' => __('Movies'),
        'singular_name' => __('Movie')
      ),
      'public' => true,
      'has_archive' => true,
      'show_in_rest' => true,
      'rest_base' => 'movies',
      'supports' => array('title', 'editor', 'custom-fields')
    )
  );
}
add_action('init', 'create_movie_post_type');

已使用 ACF 添加自定义字段,我可以在 WP 管理中查看帖子类型,并通过 site.com/wp-json/wp/v2/movies 上的直接 REST API 访问。

但是,我添加的自定义字段没有显示在 REST API 响应中。是否需要执行额外步骤才能在 REST API 中为自定义帖子类型包含 ACF 字段?

我还没有找到任何 WordPress 5.8 之后的最新资源来解决这个问题,尤其是在使用古腾堡编辑器的情况下。任何见解或最新指南的链接将不胜感激。

php wordpress
1个回答
0
投票

我假设您没有使用 ACF PRO,如果您在这里,这里有一个可能有用的链接

如果您没有 ACF PRO,则需要采取额外的步骤,在自定义帖子类型 (CPT) 的 REST API 响应中包含高级自定义字段 (ACF) 字段。默认情况下,ACF 字段不包含在自定义帖子类型的 REST API 响应中。您可以执行以下操作:

注册要包含在 REST API 响应中的 ACF 字段:ACF 提供了在 REST API 响应中包含字段的设置。您需要确保与自定义帖子类型关联的 ACF 字段设置为包含在 REST API 中。您可以在“位置”规则下的字段组设置中找到此设置。确保选中“Rest API”选项。

使用 register_rest_field 函数:如果您以编程方式注册自定义帖子类型,则可以使用 register_rest_field 函数来注册要包含在 REST API 响应中的其他字段。您可以连接到rest_api_init 操作来执行此操作。这是一个例子:

function add_custom_fields_to_rest_api() {
    // Replace 'your_post_type' with the name of your custom post type
    register_rest_field( 'your_post_type', 'your_acf_field_name', array(
        'get_callback' => 'get_acf_field_value',
        'update_callback' => null,
        'schema' => null,
    ));
}

function get_acf_field_value( $object, $field_name, $request ) {
    // Replace 'your_acf_field_name' with the name of your ACF field
    return get_field( 'your_acf_field_name', $object['id'] );
}

add_action( 'rest_api_init', 'add_custom_fields_to_rest_api' );

将“your_post_type”替换为您的自定义帖子类型的名称,将“your_acf_field_name”替换为您的 ACF 字段的名称。

© www.soinside.com 2019 - 2024. All rights reserved.