Подтвердить что ты не робот

Отменить данные из WordPress API (wp-json)

Я уже могу отключить (удалить специфику из обычных сообщений) в json, возвращенном из WordPress API. В этом примере я использую следующее ниже: https://css-tricks.com/using-the-wp-api-to-fetch-posts/

У меня возникают проблемы и не могу понять, как это изменить, чтобы он не загружал данные из Custom Post Type

Мысли?

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

Ответ 1

Для 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 );
    }
}

Замените "Страницы" на "MyCustomPostTypes" и на странице с "mycustomposttype". Просто будьте осторожны, чтобы не переименовать внутренний код 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: 
 */

Ответ 2

Если возможно, только примеры, показанные в Интернете, следующие:

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)) {
        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);//НЕПРАВИЛЬНО

Если пользовательский тип сообщения:   add_filter (' rest_prepare _ {$ post_type}' 'qod_remove_extra_data', 12, 3);

ПРИМЕР: Название post type = product;    add_filter (' rest_prepare_product' 'qod_remove_extra_data', 12, 3);

С помощью этого кода можно удалить поля, которые вы хотите использовать JSON. Используя rest_prepare} _ {$ post_type, вы решили, что вы удалили все поля post_type, тем самым повлияли только на тип post_type и не все.

Ответ 3

Не следует отличать данные от пользовательских типов сообщений, чем от встроенных типов сообщений. Вы подтвердили, что ваш вызов API фактически возвращает ваши CPT? Во-первых, вы должны посмотреть на значение того, что возвращается: http://yourwebsite.com/wp-json/posts/types. Предполагая, что ваш тип CPT появляется там, вы должны иметь возможность запрашивать элементы этого типа, например. product, вызывая: http://yourwebsite.com/wp-json/posts?type=product.

Другими словами, вы должны не изменить имя фильтра: вы все равно хотите привязать его к json_prepare_post. Если вы хотите сделать свой фильтр чувствительным к типу 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.