web-dev-qa-db-fra.com

Supprimer les données dans le type de publication personnalisé WordPress API (wp-json)

Je peux déjà désélectionner (supprimer les spécificités des publications normales) dans le JSON renvoyé par l'API WordPress. En fait, j'utilise ce qui suit dans cet exemple: https://css-tricks.com/using-the-wp-api-to-fetch-posts/

Ce que j’ai du mal à comprendre et à savoir, c’est comment changer cela afin que les données soient effacées d’un Type de message personnalisé

Pensées?

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

nouvel exemple avec type de message personnalisé **

function projectPost_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'] );



  return $data;
}

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

Si possible, seuls les exemples présentés sur Internet sont:

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

et à droite est:

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

IMPORTANT: Est-ce que:

add_filter ('**rest_prepare_post**', 'qod_remove_extra_data', 12, 3);

Ne pas:

add_filter ('**json_prepare_post**' 'qod remove extra_data', 12, 3); //WRONG (No underscores)

Si le type de message personnalisé est:

add_filter ('**rest_prepare_{$post_type}**', 'qod_remove_extra_data', 12, 3);

EXEMPLE: Nom poste type = produit;

 add_filter ('**rest_prepare_product**', 'qod_remove_extra_data', 12, 3);

Avec ce code peut supprimer les champs que vous voulez le JSON. En utilisant rest_prepare} _ {$ post_type, décidez que vous avez éliminé tous les champs post_type et n’affectera donc que le post_type souhaité, mais pas tous.

Consultez le code wp-api pour les pages (qui sont des types de publication personnalisés).

Vous pouvez modifier le code, en changeant les pages selon le type de message que vous appelez (faites attention à ne pas faire de recherche et remplacez toutes les "pages" car certaines d'entre elles sont des appels de fonction wordpress ou des filtres)

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

Mettez votre code personnalisé dans edit ou filter etc, et c'est parti!

ps - n'oubliez pas de le transformer en un plugin approprié! Vous pouvez ajouter un nouveau plugin et le gérer mieux en utilisant:

<?php
/**
 * Plugin Name: My JSON App API
 * Description: My Route and Endpoint handler for the JSON API
 * Dependency:  This plugin requires JSON BasicKey Authentication Plugin!!!! 
 * Author: Blah Blah Blah, plus much original code from the WordPress API Team
 * Author URI: https://www.example.com
 * Version: 1.2
 * Plugin URI: https://www.example.com
 */

if ( ! defined( 'ABSPATH' ) ) exit; // Exit if accessed directly
if (!defined("MY_JSON_API_VERSION")) {
    define ("MY_JSON_API_VERSION",  "1.2") ;
}

function my_json_api_init() {
    global $my_json_api_mobile_users;
    $my_json_api_mobile_users = new my_JSON_API_MobileUsers();
    add_filter( 'json_endpoints', array( $my_json_api_mobile_users, 'register_routes' ) );
}
add_action( 'wp_json_server_before_serve', 'my_json_api_init' );
0
brianlmerritt