用于显示高级自定义字段的 JSON API - WordPress

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10132685/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 18:17:44  来源:igfitidea点击:

JSON API to show Advanced Custom Fields - WordPress

jsonwordpress

提问by SPillai

I am developing a magazine WordPress site that will have a json feed for a Mobile App. I set the backend up using Advanced Custom Fields with a Repeater Field for Multiple Articles and Multiple Pages within each article. http://www.advancedcustomfields.com/add-ons/repeater-field/Screen shot of Repeater Fields

我正在开发一个杂志 WordPress 网站,该网站将为移动应用程序提供 json 提要。我使用高级自定义字段设置后端,并为每篇文章中的多篇文章和多页使用转发器字段。http://www.advancedcustomfields.com/add-ons/repeater-field/中继器字段的屏幕截图

I am using the JSON API but this does not include any of my custom fields. Is there currently a plugin that can do this?

我正在使用 JSON API,但这不包括我的任何自定义字段。目前有可以做到这一点的插件吗?

These are the Custom Fields 'slug names' of the previous fields

这些是之前字段的自定义字段“slug 名称”

回答by jake

@Myke: you helped me tremendously. Here's my humble addition:

@Myke:你帮了我很大的忙。这是我谦虚的补充:

add_filter('json_api_encode', 'json_api_encode_acf');


function json_api_encode_acf($response) 
{
    if (isset($response['posts'])) {
        foreach ($response['posts'] as $post) {
            json_api_add_acf($post); // Add specs to each post
        }
    } 
    else if (isset($response['post'])) {
        json_api_add_acf($response['post']); // Add a specs property
    }

    return $response;
}

function json_api_add_acf(&$post) 
{
    $post->acf = get_fields($post->id);
}

回答by Myke Bates

Came here by searching with the same question. This isn't totally vetted yet but I think this is getting on the right path. Check it out.

通过搜索相同的问题来到这里。这还没有完全经过,但我认为这是在正确的道路上。一探究竟。

I have one less nested level than you do so this might need altered a bit. But the JSON API plugin has a filter called json_api_encode. I have a repeater called specifications that looks like this.

我的嵌套级别比你少,所以这可能需要稍微改变一下。但是 JSON API 插件有一个名为 json_api_encode 的过滤器。我有一个叫做规格的中继器,看起来像这样。

http://d.pr/i/YMvv

http://d.pr/i/YMvv

In my functions file I have this.

在我的函数文件中,我有这个。

add_filter('json_api_encode', 'my_encode_specs');

function my_encode_specs($response) {
  if (isset($response['posts'])) {
    foreach ($response['posts'] as $post) {
      my_add_specs($post); // Add specs to each post
    }
  } else if (isset($response['post'])) {
    my_add_specs($response['post']); // Add a specs property
  }
  return $response;
}

function my_add_specs(&$post) {
  $post->specs = get_field('specifications', $post->id);
}

Which appends a custom value to the JSON API output. Notice the get_field function from ACF works perfectly here for bringing back the array of the repeater values.

它将自定义值附加到 JSON API 输出。请注意,ACF 的 get_field 函数在这里可以完美地返回中继器值的数组。

Hope this helps!

希望这可以帮助!

回答by Chris

Update for Wordpress 4.7

WordPress 4.7更新

With the release of Wordpress 4.7 the REST functionality is no longer provided as a distinct plugin, rather its rolled in (no plugin required).

随着 Wordpress 4.7 的发布,REST 功能不再作为一个独特的插件提供,而是推出了(不需要插件)。

The previous filters don't appear to work. However the following snippet does (can be in your functions.php):

以前的过滤器似乎不起作用。但是,以下代码段可以(可以在您的 中functions.php):

>= PHP 5.3

>= PHP 5.3

add_filter('rest_prepare_post', function($response) {
    $response->data['acf'] = get_fields($response->data['id']);
    return $response;
});

< PHP 5.3

< PHP 5.3

add_filter('rest_prepare_post', 'append_acf');

function append_acf($response) {
    $response->data['acf'] = get_fields($response->data['id']);
    return $response;
};

Note the filter is a wild card filter, applied like

注意过滤器是一个通配符过滤器,应用如下

apply_filters("rest_prepare_$type", ...

so if you have multiple content types (custom), you will need to do:

因此,如果您有多种内容类型(自定义),则需要执行以下操作:

add_filter('rest_prepare_multiple_choice', 'append_acf');
add_filter('rest_prepare_vocabularies', 'append_acf');

function append_acf($response) {
    $response->data['acf'] = get_fields($response->data['id']);
    return $response;
};

NoteIt appears that rest_prepare_xis called per record. So if you are pinging the index endpoint, it will be called multiple times (so you don't need to check if its posts or post)

注意它似乎rest_prepare_x按记录调用的。因此,如果您正在 ping 索引端点,它将被多次调用(因此您无需检查其帖子或帖子)

回答by Blowsie

There is now a small plugin which adds the filter for you.

现在有一个小插件可以为您添加过滤器。

https://github.com/PanManAms/WP-JSON-API-ACF

https://github.com/PanManAms/WP-JSON-API-ACF

回答by killianlgrant

I'm not sure if you're still interested in a solution, but I was able to modify the json-api plugin models/post.php file to display the repeater data as an array. This is a modification of a modification made by http://wordpress-problem.com/marioario-on-plugin-json-api-fixed-get-all-custom-fields-the-right-way/

我不确定您是否仍然对解决方案感兴趣,但我能够修改 json-api 插件 models/post.php 文件以将转发器数据显示为数组。这是对http://wordpress-problem.com/marioario-on-plugin-json-api-fixed-get-all-custom-fields-the-right-way/所做的修改的修改

replace the set_custom_fields_value() function with the following:

将 set_custom_fields_value() 函数替换为以下内容:

function set_custom_fields_value() {

    global $json_api;

    if ($json_api->include_value('custom_fields') && $json_api->query->custom_fields) {

        // Query string params for this query var
        $params = trim($json_api->query->custom_fields);

        // Get all custom fields if true|all|* is passed
        if ($params === "*" || $params === "true" || $params === "all") {

            $wp_custom_fields = get_post_custom($this->id);
            $this->custom_fields = new stdClass();

            // Loop through our custom fields and place on property
            foreach($wp_custom_fields as $key => $val) {
                if (get_field($key)) {
                    $this->custom_fields->$key = get_field($key);
                } else if ($val) {
                    // Some fields are stored as serialized arrays.
                    // This method does not support multidimensionals... 
                    // but didn't see anything wrong with this approach
                    $current_custom_field = @unserialize($wp_custom_fields[$key][0]);

                    if (is_array($current_custom_field)) {

                        // Loop through the unserialized array
                        foreach($current_custom_field as $sub_key => $sub_val) {

                            // Lets append these for correct JSON output
                            $this->custom_fields->$key->$sub_key = $sub_val;
                        }

                    } else {

                        // Break this value of this custom field out of its array
                        // and place it on the stack like usual
                        $this->custom_fields->$key = $wp_custom_fields[$key][0];

                    }
                }
            }
        } else {

            // Well this is the old way but with the unserialized array fix
            $params = explode(',', $params);
            $wp_custom_fields = get_post_custom($this->id);
            $this->custom_fields = new stdClass();

            foreach ($params as $key) {

                if (isset($wp_custom_fields[$key]) && $wp_custom_fields[$key][0] ) {
                    $current_custom_field = @unserialize($wp_custom_fields[$key][0]);

                    if (is_array($current_custom_field)) {
                        foreach($current_custom_field as $sub_key => $sub_val) {
                            $this->custom_fields->$key->$sub_key = $sub_val;
                        }

                    } else {
                        $this->custom_fields->$key = $wp_custom_fields[$key][0];

                    }

                }
            }
        }

    } else {
        unset($this->custom_fields);

    }
}

回答by matteobelfiore

Current version of ACF prints out a custom_fields object on a call to the JSON API, containing all the fields relative to the Post or Page. I edited @Myke version to add specific custom fields from the ACF Option page to each Post or Page. Unfortunately there is not get_fields() function for the whole Option Page so you'll have to edit it depending on your fields structure.

当前版本的 ACF 在调用 JSON API 时打印出一个 custom_fields 对象,其中包含与 Post 或 Page 相关的所有字段。我编辑了@Myke 版本,将 ACF 选项页面中的特定自定义字段添加到每个帖子或页面。不幸的是,整个选项页面没有 get_fields() 函数,因此您必须根据您的字段结构对其进行编辑。

add_filter('json_api_encode', 'json_api_encode_acf');

function json_api_encode_acf($response) {
    if (isset($response['posts'])) {
        foreach ($response['posts'] as $post) {
            json_api_add_acf($post); // Add specs to each post
        }
    }
    else if (isset($response['post'])) {
        json_api_add_acf($response['post']); // Add a specs property
    }
    else if (isset($response['page'])) {
        json_api_add_acf($response['page']); // Add a specs to a page
    }

    return $response;
}

function json_api_add_acf(&$post) {
    $post->custom_fields->NAME_OF_YOUR_CUSTOM_FIELD = get_field( 'NAME_OF_YOUR_CUSTOM_FIELD', 'option' );
}