programing

WordPress API의 데이터 설정 해제(wp-json)

newnotes 2023. 3. 11. 09:26
반응형

WordPress API의 데이터 설정 해제(wp-json)

WordPress API에서 반환된 json에서 이미 설정 해제(일반 게시물에서 자세한 내용은 삭제)할 수 있습니다.이 예에서 실제로 사용하고 있는 것은 https://css-tricks.com/using-the-wp-api-to-fetch-posts/ 입니다.

문제가 있어 이해할 수 없는 것은 커스텀 투고 타입에서 데이터 설정을 해제하도록 변경하는 방법입니다.

생각?

function qod_remove_extra_data( $data, $post, $context ) {
  // We only want to modify the 'view' context, for reading posts
  if ( $context !== 'view' || is_wp_error( $data ) ) {
    return $data;
  }

  // Here, we unset any data we don't want to see on the front end:
  unset( $data['author'] );
  unset( $data['status'] );
  unset( $data['featured_image'] );
  //etc etc

  return $data;
}

add_filter( 'json_prepare_post', 'qod_remove_extra_data', 12, 3 );

커스텀 투고유형의 예 필터:

function projectPost_remove_extra_data( $data, $post, $context ) {

  if ( $context !== 'view' || is_wp_error( $data ) ) {
    return $data;
  }

  // Here, we unset any data we don't want to see on the front end:
  unset( $data['author'] );



  return $data;
}

add_filter( 'json_prepare_project', 'projectPost_remove_extra_data', 12, 3 );

wp-api v1.x의 경우 확장해야 합니다.WP_JSON_CustomPostType페이지 파일에 예가 있습니다.class-wp-json-pages.php)

<?php
/**
 * Page post type handlers
 *
 * @package WordPress
 * @subpackage JSON API
 */

/**
 * Page post type handlers
 *
 * This class serves as a small addition on top of the basic post handlers to
 * add small functionality on top of the existing API.
 *
 * In addition, this class serves as a sample implementation of building on top
 * of the existing APIs for custom post types.
 *
 * @package WordPress
 * @subpackage JSON API
 */
class WP_JSON_Pages extends WP_JSON_CustomPostType {
    /**
     * Base route
     *
     * @var string
     */
    protected $base = '/pages';

    /**
     * Post type
     *
     * @var string
     */
    protected $type = 'page';

    /**
     * Register the page-related routes
     *
     * @param array $routes Existing routes
     * @return array Modified routes
     */
    public function register_routes( $routes ) {
        $routes = parent::register_routes( $routes );
        $routes = parent::register_revision_routes( $routes );
        $routes = parent::register_comment_routes( $routes );

        // Add post-by-path routes
        $routes[ $this->base . '/(?P<path>.+)'] = array(
            array( array( $this, 'get_post_by_path' ),    WP_JSON_Server::READABLE ),
            array( array( $this, 'edit_post_by_path' ),   WP_JSON_Server::EDITABLE | WP_JSON_Server::ACCEPT_JSON ),
            array( array( $this, 'delete_post_by_path' ), WP_JSON_Server::DELETABLE ),
        );

        return $routes;
    }

    /**
     * Retrieve a page by path name
     *
     * @param string $path
     * @param string $context
     *
     * @return array|WP_Error
     */
    public function get_post_by_path( $path, $context = 'view' ) {
        $post = get_page_by_path( $path, ARRAY_A );

        if ( empty( $post ) ) {
            return new WP_Error( 'json_post_invalid_id', __( 'Invalid post ID.' ), array( 'status' => 404 ) );
        }

        return $this->get_post( $post['ID'], $context );
    }

    /**
     * Edit a page by path name
     *
     * @param $path
     * @param $data
     * @param array $_headers
     *
     * @return true|WP_Error
     */
    public function edit_post_by_path( $path, $data, $_headers = array() ) {
        $post = get_page_by_path( $path, ARRAY_A );

        if ( empty( $post ) ) {
            return new WP_Error( 'json_post_invalid_id', __( 'Invalid post ID.' ), array( 'status' => 404 ) );
        }

        return $this->edit_post( $post['ID'], $data, $_headers );
    }

    /**
     * Delete a page by path name
     *
     * @param $path
     * @param bool $force
     *
     * @return true|WP_Error
     */
    public function delete_post_by_path( $path, $force = false ) {
        $post = get_page_by_path( $path, ARRAY_A );

        if ( empty( $post ) ) {
            return new WP_Error( 'json_post_invalid_id', __( 'Invalid post ID.' ), array( 'status' => 404 ) );
        }

        return $this->delete_post( $post['ID'], $force );
    }

    /**
     * Prepare post data
     *
     * @param array $post The unprepared post data
     * @param string $context The context for the prepared post. (view|view-revision|edit|embed|single-parent)
     * @return array The prepared post data
     */
    protected function prepare_post( $post, $context = 'view' ) {
        $_post = parent::prepare_post( $post, $context );

        // Override entity meta keys with the correct links
        $_post['meta']['links']['self'] = json_url( $this->base . '/' . get_page_uri( $post['ID'] ) );

        if ( ! empty( $post['post_parent'] ) ) {
            $_post['meta']['links']['up'] = json_url( $this->base . '/' . get_page_uri( (int) $post['post_parent'] ) );
        }

        return apply_filters( 'json_prepare_page', $_post, $post, $context );
    }
}

"페이지"를 "My Custom Post"로 바꿉니다.유형" 및 "mycustompost type" 페이지를 참조하십시오.내부 WordPress 코드의 이름을 변경하지 않도록 주의하십시오.page

참고: JSON-WP-API 플러그인을 변경하는 대신 플러그인으로 추가하는 것이 좋습니다.

/**
 * Plugin Name: MyCustom JSON App API
 * Description: MyCustomPost handler for the JSON API
 * Dependency:  This plugin requires JSON-WP-API Plugin!!!! 
 * Author: 
 * Author URI: 
 * Version: 
 * Plugin URI: 
 */

가능한 경우 인터넷에 표시되는 예는 다음과 같습니다.

function qod_remove_extra_data ($ data, $ post, $ context) {
    // We only want to modify the 'view' context, for reading posts 
    if ($ context! == 'view' || is_wp_error ($ data)) {
        return $ data; 
    } 
    // Here, we unset any data we do not want to see on the front end: 
    unset ($data ['author']); 
    unset ($data ['status']); 
    // Continue unsetting whatever other fields you want return $ data;
}
add_filter ('json_prepare_post' 'qod remove extra_data', 12, 3);

오른쪽은 다음과 같습니다.

qod_remove_extra_data function ($ data, $ post, $ context) {
    // We only want to modify the 'view' context, for reading posts 
    if ($ context! == 'view' || is_wp_error ($ data)) {
         unset ( $data->data ['excerpt']); //Example
         unset ($data->data ['content']); //Example
         unset ($data->data ['name field to remove']) 
         //or 
         unset ($data->data ['name field to remove'] ['name subfield if you only want to delete the sub-field of field' ]) 
         return $data; 
     }
}
add_filter ('rest_prepare_post' 'qod_remove_extra_data', 12, 3);

중요: add_filter('rest_prepare_post' 'qod_remove_extra_data', 12, 3);

없음: add_filter('json_prepare_post' 'qod remove extra_data', 12, 3); //WRONG

가 커스텀 투고 타입인 경우: add_filter('rest_prepare_{$post_type}' 'qod_remove_extra_data', 12, 3)

예: 게시물 유형 = 제품, add_filter('rest_filter_product' 'qod_remove_filter_data', 12, 3)의 이름을 지정합니다.

이 코드를 사용하면 JSON에서 원하는 필드를 삭제할 수 있습니다.rest_prepare} _ {$ post_type을 사용하여 모든 post_type 필드를 삭제하였으므로 모든 post_type에 영향을 주지 않고 원하는 post_type에만 영향을 미쳤다고 판단합니다.

커스텀 포스트 타입에서 데이터를 삭제하는 것은 빌트인 포스트 타입과 다를 바 없습니다.API 콜이 실제로 CPT를 반환하고 있는지 확인했습니까?먼저 다음에서 반환되는 항목의 가치를 살펴봐야 합니다.http://yourwebsite.com/wp-json/posts/typesCPT 타입이 표시되어 있는 경우는, 그 타입의 아이템을 문의할 수 있습니다.product, 호출:http://yourwebsite.com/wp-json/posts?type=product.

즉, 필터의 이름을 변경할 수 없습니다.여전히 이 필터의 이름을json_prepare_post필터를 투고 타입에 민감하게 하고 CPT가 있는 경우에만 특정 필드를 삭제하려면 다음과 같이 하십시오.

function my_remove_extra_product_data( $data, $post, $context ) {
    // make sure you've got the right custom post type
    if ( 'product' !== $data[ 'type' ] ) {
        return $data;
    }
    // now proceed as you saw in the other examples
    if ( $context !== 'view' || is_wp_error( $data ) ) {
        return $data;
    }
    // unset unwanted fields
    unset( $data[ 'author' ] );

    // finally, return the filtered data
    return $data;
}

// make sure you use the SAME filter hook as for regular posts
add_filter( 'json_prepare_post', 'my_remove_extra_product_data', 12, 3 );

자세한 내용은 WP API Getting Started Guide를 참조하십시오.

언급URL : https://stackoverflow.com/questions/32511201/unset-data-from-wordpress-api-wp-json

반응형