programing

고급 사용자 지정 필드를 표시하는 JSON API - WordPress

css3 2023. 3. 21. 22:26

고급 사용자 지정 필드를 표시하는 JSON API - WordPress

모바일 앱용 json 피드를 탑재한 잡지 Word Press 사이트를 개발 중입니다.각 기사 내의 여러 기사 및 여러 페이지에 대한 리피터 필드가 있는 고급 커스텀 필드를 사용하여 백엔드를 셋업했습니다.http://www.advancedcustomfields.com/add-ons/repeater-field/ 리피터 필드 스크린샷

JSON API를 사용하고 있지만 커스텀필드는 포함되어 있지 않습니다.현재 이 기능을 사용할 수 있는 플러그인이 있습니까?

이전 필드의 사용자 지정 필드 '슬래그 이름'입니다.

@마이크: 당신은 나에게 큰 도움을 주었다.여기 저의 작은 추가사항이 있습니다.

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);
}

Wordpress 4.7 업데이트

Wordpress 4.7 릴리즈에서 REST 기능은 더 이상 별도의 플러그인으로 제공되지 않고 롤인됩니다(플러그인 불필요).

을 사용법, 다음 (자신의 ,, 음, 음에 포함될 수 )functions.php

>= PHP 5.3

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

< PHP 5.3

add_filter('rest_prepare_post', 'append_acf');

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

필터는 와일드카드 필터로 다음과 같이 적용됩니다.

apply_filters("rest_prepare_$type", ...

복수의 컨텐츠 타입(커스텀)이 있는 경우는, 다음의 조작을 실시할 필요가 있습니다.

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;
};

주의:rest_prepare_x레코드 단위로 호출됩니다.따라서 인덱스 엔드포인트에 ping을 실행하면 여러 번 호출됩니다(따라서 해당 게시물 또는 게시물 여부를 확인할 필요가 없습니다).

같은 질문으로 검색해서 왔습니다.이것은 아직 완전히 검증되지는 않았지만 나는 이것이 올바른 방향으로 가고 있다고 생각한다.이것을 확인해 보세요.

네스트 레벨이 당신보다 하나 적기 때문에 조금 수정해야 할 것 같습니다.그러나 JSON API 플러그인에는 json_api_encode라는 필터가 있습니다.이렇게 생긴 사양이라는 리피터가 있어요.

http://d.pr/i/YMvv

제 함수 파일에 이런 게 있어요.

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);
}

그러면 커스텀 값이 JSON API 출력에 추가됩니다.여기서 ACF로부터의 get_field 함수는 리피터 값의 배열을 되돌리기 위해 완벽하게 기능합니다.

이게 도움이 됐으면 좋겠네요!

필터를 추가하는 작은 플러그인이 있습니다.

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

아직 솔루션에 관심이 있는지 모르겠지만, json-api 플러그인 모델/post.php 파일을 수정하여 리피터 데이터를 배열로 표시할 수 있었습니다.이것은 http://wordpress-problem.com/marioario-on-plugin-json-api-fixed-get-all-custom-fields-the-right-way/에서 수정한 내용입니다.

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);

    }
}

현재 버전의 ACF는 Post 또는 Page에 관련된 모든 필드를 포함하는 custom_fields 객체를 JSON API 호출로 출력합니다.@Myke version을 편집하여 ACF Option 페이지에서 각 Post 또는 Page에 특정 커스텀 필드를 추가하였습니다.유감스럽게도 옵션 페이지 전체에 대한 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' );
}

언급URL : https://stackoverflow.com/questions/10132685/json-api-to-show-advanced-custom-fields-wordpress