programing

WP REST API V2를 통해 사용자 정의 필드로 Custom Post Type을 올바르게 작성하는 방법

telecom 2023. 11. 1. 22:08
반응형

WP REST API V2를 통해 사용자 정의 필드로 Custom Post Type을 올바르게 작성하는 방법

사용자 지정 필드가 있는 wprest api v2를 통해 사용자 지정 게시 유형 레코드를 올바르게 만드는 방법은 무엇입니까?사용자 지정 필드를 만들거나 업데이트할 수 없습니다.

저는 수퍼리스트와 수퍼리스트-차일드 테마를 자체 호스팅 워드프레스 설치에 설치했습니다.

이 테마는 Custom Post Type에 대한 Custom Tecosomies를 사용하여 카테고리, 위치, 비즈니스라고 불리는 Custom Post Type 및 Custom Meta의 Custom 필드를 사용합니다.

저는 rest api v2를 사용하여 사이트로 데이터를 가져오려고 노력하고 있으며 사용자 정의 카테고리와 위치를 성공적으로 만들었습니다.REST API Enabler 플러그인을 사용하여 사용자 지정 엔드포인트와 사용자 지정 필드를 등록했습니다.

비즈니스 엔드포인트 사용http://mysite/wp-json/wp/v2/businessesapi를 통해 새로운 비즈니스를 업로드 할 수 있지만 생성된 레코드는 모든 메타 키를 무시합니다.

예. 다음과 같은 신체가 주어집니다.

      body = {
        title: company_name,
        listing_address: [address], 
        listing_map_location_latitude: [c.lat],
        listing_map_location_longitude: [c.lon],
        content: c.description,
        email: c.email,
        facebook: [c.facebook],
        image_url: c.image_url,
        locations: [c.city.server_id],
        listing_categories: c.categories.pluck(:server_id),
        listing_street_view: ["on"]
        status:"publish"
      }
      request = HTTParty.post(POSTS_END_POINT, body: body, headers: headers)

REST api를 통해 이전에 생성된 올바른 위치 및 사용자 지정 범주(listing_categories)에 비즈니스를 올바르게 연결하지만 사용자 지정 필드(wp_postmeta table)가 채워지지 않습니다.listing_locations외밭과 밭 그리고listing_address

나머지 api를 통해 업로드된 레코드를 조회할 수 있는데 이렇게 답변이 옵니다.

$ rake upload:test
Result: {"id"=>1749, "date"=>"2016-02-20T05:06:01", "date_gmt"=>nil, "guid"=>{"rendered"=>"http://highstreetbeacons.com/?post_type=business&p=1749"}, "modified"=>"2016-02-20T05:06:01", "modified_gmt"=>nil, "slug"=>"", "type"=>"business", "link"=>"http://highstreetbeacons.com/?post_type=business&p=1749", "title"=>{"rendered"=>"Birmingham Museum and Art Gallery, Chamberlain Square, Birmingham, B3 3DH"}, "content"=>{"rendered"=>"<p>A description</p>\n"}, "author"=>1, "featured_media"=>0, "comment_status"=>"open", "ping_status"=>"closed", "listing_categories"=>[3779, 4095, 4061], "locations"=>[330], "_links"=>{"self"=>[{"href"=>"http://highstreetbeacons.com/wp-json/wp/v2/businesses/1749"}], "collection"=>[{"href"=>"http://highstreetbeacons.com/wp-json/wp/v2/businesses"}], "about"=>[{"href"=>"http://highstreetbeacons.com/wp-json/wp/v2/types/business"}], "author"=>[{"embeddable"=>true, "href"=>"http://highstreetbeacons.com/wp-json/wp/v2/users/1"}], "replies"=>[{"embeddable"=>true, "href"=>"http://highstreetbeacons.com/wp-json/wp/v2/comments?post=1749"}], "https://api.w.org/attachment"=>[{"href"=>"http://highstreetbeacons.com/wp-json/wp/v2/media?parent=1749"}], "https://api.w.org/term"=>[{"taxonomy"=>"listing_categories", "embeddable"=>true, "href"=>"http://highstreetbeacons.com/wp-json/wp/v2/listing_categories?post=1749"}, {"taxonomy"=>"locations", "embeddable"=>true, "href"=>"http://highstreetbeacons.com/wp-json/wp/v2/locations?post=1749"}]}}

이것은 메타 키를 완전히 무시하는 것입니다.관리 영역에서 수동으로 생성된 비즈니스에 대한 업데이트 버튼을 누른 경우 API를 통해 다시 쿼리하고 올바른 필드를 모두 반환할 수 있지만 업데이트할 POST 요청(반드시 PUT이어야 함)은 레코드에서 여전히 사용자 지정 필드를 설정하지 않습니다.

예.

rake upload:test
Result: {"id"=>1745, "date"=>"2016-02-20T04:53:17", "date_gmt"=>nil, "guid"=>{"rendered"=>"http://highstreetbeacons.com/?post_type=business&#038;p=1745"}, "modified"=>"2016-02-20T04:53:17", "modified_gmt"=>"2016-02-20T04:53:17", "slug"=>"", "type"=>"business", "link"=>"http://highstreetbeacons.com/?post_type=business&p=1745", "title"=>{"rendered"=>"Birmingham Museum and Art Gallery, Chamberlain Square, Birmingham, B3 3DH"}, "content"=>{"rendered"=>"<p>A description</p>\n"}, "author"=>1, "featured_media"=>0, "comment_status"=>"open", "ping_status"=>"closed", "listing_categories"=>[3779, 4095, 4061], "locations"=>[330], "listing_featured_image"=>[""], "listing_banner"=>["banner_featured_image"], "listing_opening_hours"=>["a:7:{i:0;a:4:{s:11:\"listing_day\";s:6:\"MONDAY\";s:17:\"listing_time_from\";s:0:\"\";s:15:\"listing_time_to\";s:0:\"\";s:14:\"listing_custom\";s:0:\"\";}i:1;a:4:{s:11:\"listing_day\";s:7:\"TUESDAY\";s:17:\"listing_time_from\";s:0:\"\";s:15:\"listing_time_to\";s:0:\"\";s:14:\"listing_custom\";s:0:\"\";}i:2;a:4:{s:11:\"listing_day\";s:9:\"WEDNESDAY\";s:17:\"listing_time_from\";s:0:\"\";s:15:\"listing_time_to\";s:0:\"\";s:14:\"listing_custom\";s:0:\"\";}i:3;a:4:{s:11:\"listing_day\";s:8:\"THURSDAY\";s:17:\"listing_time_from\";s:0:\"\";s:15:\"listing_time_to\";s:0:\"\";s:14:\"listing_custom\";s:0:\"\";}i:4;a:4:{s:11:\"listing_day\";s:6:\"FRIDAY\";s:17:\"listing_time_from\";s:0:\"\";s:15:\"listing_time_to\";s:0:\"\";s:14:\"listing_custom\";s:0:\"\";}i:5;a:4:{s:11:\"listing_day\";s:8:\"SATURDAY\";s:17:\"listing_time_from\";s:0:\"\";s:15:\"listing_time_to\";s:0:\"\";s:14:\"listing_custom\";s:0:\"\";}i:6;a:4:{s:11:\"listing_day\";s:6:\"SUNDAY\";s:17:\"listing_time_from\";s:0:\"\";s:15:\"listing_time_to\";s:0:\"\";s:14:\"listing_custom\";s:0:\"\";}}"], "listing_map_location"=>["a:2:{s:8:\"latitude\";s:0:\"\";s:9:\"longitude\";s:0:\"\";}"], "listing_street_view_location_latitude"=>["37.812405"], "listing_street_view_location_longitude"=>["-122.47607800000003"], "listing_street_view_location_heading"=>["-18"], "listing_street_view_location"=>["a:5:{s:8:\"latitude\";s:9:\"37.812405\";s:9:\"longitude\";s:19:\"-122.47607800000003\";s:4:\"zoom\";s:1:\"1\";s:7:\"heading\";s:3:\"-18\";s:5:\"pitch\";s:2:\"25\";}"], "listing_locations"=>["a:1:{i:0;s:10:\"birmingham\";}"], "listing_listing_category"=>["a:3:{i:0;s:7:\"museums\";i:1;s:10:\"coffee-tea\";i:2;s:13:\"art-galleries\";}"], "_links"=>{"self"=>[{"href"=>"http://highstreetbeacons.com/wp-json/wp/v2/businesses/1745"}], "collection"=>[{"href"=>"http://highstreetbeacons.com/wp-json/wp/v2/businesses"}], "about"=>[{"href"=>"http://highstreetbeacons.com/wp-json/wp/v2/types/business"}], "author"=>[{"embeddable"=>true, "href"=>"http://highstreetbeacons.com/wp-json/wp/v2/users/1"}], "replies"=>[{"embeddable"=>true, "href"=>"http://highstreetbeacons.com/wp-json/wp/v2/comments?post=1745"}], "https://api.w.org/attachment"=>[{"href"=>"http://highstreetbeacons.com/wp-json/wp/v2/media?parent=1745"}], "https://api.w.org/term"=>[{"taxonomy"=>"listing_categories", "embeddable"=>true, "href"=>"http://highstreetbeacons.com/wp-json/wp/v2/listing_categories?post=1745"}, {"taxonomy"=>"locations", "embeddable"=>true, "href"=>"http://highstreetbeacons.com/wp-json/wp/v2/locations?post=1745"}]}}

REST API Enabler 플러그인에 의존하지 않고 사용자 지정 필드를 등록하기 위해 플러그인을 방금 만들었습니다.

<?php
/**
 * Plugin Name: Jamesc Register API Fields
 * Plugin URI: http://danielpataki.com
 * Description: This plugin exposes business meta data mfields to REST API.
 * Version: 1.0.0
 * Author: Smiler
 */


/**
 * Use arbitrary functions to add a field
 */
add_action( 'rest_api_init', 'register_something_random' );
function slug_register_something_random() {
    register_rest_field( 'business',
        'listing_address',
        array(
            'get_callback'    => 'get_meta_field',
            'update_callback' => 'update_meta_field',
            'schema'          => null,
        )
    );
}

/**
 * Handler for getting custom field data.
 *
 * @since 0.1.0
 *
 * @param array $object The object from the response
 * @param string $field_name Name of field
 * @param WP_REST_Request $request Current request
 *
 * @return mixed
 */
function get_meta_field( $object, $field_name, $request ) {
    return get_post_meta( $object[ 'id' ], $field_name );
}

/**
 * Handler for updating custom field data.
 *
 * @since 0.1.0
 *
 * @param mixed $value The value of the field
 * @param object $object The object from the response
 * @param string $field_name Name of field
 *
 * @return bool|int
 */
function update_meta_field( $value, $object, $field_name ) {
    if ( ! $value || ! is_string( $value ) ) {
        return;
    }

    return update_post_meta( $object->ID, $field_name, strip_tags( $value ) );

}

하지만 이것은 효과가 없습니다.

나는 지금 내가 생각할 수 있는 모든 것을 시도하느라 완전히 꼼짝 못하고 있습니다.

내 워드프레스 플러그인에서 작업 추가 기능 이름이 실제 기능 이름과 일치하지 않는 문제가 발생했습니다.register_something_random그리고.slug_register_something_random()

add_action( 'rest_api_init', 'register_something_random' );
function slug_register_something_random() {

그래야 한다

add_action( 'rest_api_init', 'register_something_random' );
function register_something_random() {

이 변경을 했고 이제 모든 것이 정상입니다.

언급URL : https://stackoverflow.com/questions/35519680/how-to-correctly-create-custom-post-type-with-custom-fields-through-wp-rest-api

반응형