2015-09-10 21 views
12

Posso già disinserire (rimuovere le specifiche dai post normali) nel json restituito dall'API di WordPress. Io in realtà utilizzare il seguente sotto da questo esempio: https://css-tricks.com/using-the-wp-api-to-fetch-posts/Disinserimento dati da WordPress API (wp-json)

Quello che sto avendo difficoltà con e non riesco a capire, è come cambiare questo modo si disinserisce dati da un tipo personalizzato Messaggio

Pensieri?

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

personalizzato filtro Tipo di messaggio di esempio:

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

Quale versione API stai utilizzando? Sta cambiando per la v2. Si prega di consultare: https://github.com/WP-API/WP-API/issues/1195 – brianlmerritt

+0

@brainlmeritt Sto usando la versione 1 – RMH

risposta

3

Per wp-api v1.x, è necessario estendere WP_JSON_CustomPostType. V'è un esempio nel file delle pagine (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); 
    } 
} 

Sostituire "Pagine" con "MyCustomPostTypes" e la pagina con "mycustomposttype". Basta essere attenti a non rinominare il codice di WordPress interno che utilizza anche il termine page

Nota: probabilmente la cosa migliore per aggiungere questo come un plug-in piuttosto che cambiare il plugin 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: 
*/ 
1

Non dovrebbe diverso per rimuovere i dati dai tipi di post personalizzati che dai tipi di post integrati. Hai confermato che la tua chiamata API sta effettivamente restituendo i tuoi CPT? Innanzitutto, dovresti esaminare il valore di ciò che viene restituito da: http://yourwebsite.com/wp-json/posts/types. Supponendo che il tuo tipo di CPT si presenti lì, dovresti essere in grado di eseguire una query per gli articoli di quel tipo, ad es. product, chiamando: http://yourwebsite.com/wp-json/posts?type=product.

In altre parole, è necessario non modificare il nome del filtro: si desidera ancora legare in json_prepare_post. Se si vuole fare il filtro sensibile di inviare tipo e rimuovere solo alcuni campi se si dispone di un CPT si potrebbe fare qualcosa di simile:

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

È possibile trovare maggiori documentazione nel WP API Getting Started Guide.

+0

Ho aggiornato il mio esempio di lavoro a ciò che hai elencato, e non è stato in grado di disinserire qualsiasi dei dati. L'API sta funzionando e in effetti l'ho colpito con una chiamata ajax per ottenere il titolo, il campo acf e l'area del contenuto. – RMH

+0

potresti fornire un link al tuo sito? – morphatic

+0

ah, va bene, suona bene. All'interno della funzione, come prima riga, aggiungere quanto segue: 'echo'

' . print_r($data) . '
'; esci; e eseguilo di nuovo. Questo dovrebbe fare un dump var della variabile '$ data'. È molto probabile che stiamo tentando di annullare l'impostazione di variabili che non esistono o che stiamo cercando di accedere ai membri degli oggetti come indici di array. – morphatic

2

se possibile, solo gli esempi mostrati in internet è:

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

e destra è:

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

IMPORTANTE: Is: add_filter ('rest_prepare_post' 'qod_remove_extra_data ', 12, 3);

Non

: add_filter ('json_prepare_post' 'remove extra_data qod', 12, 3); // SBAGLIATO

Se è personalizzato Tipo messaggio: add_filter ('rest_prepare _ {$ post_type}' 'qod_remove_extra_data', 12, 3);

ESEMPIO: Nome tipo di post = prodotto; add_filter ('rest_prepare_product' 'qod_remove_extra_data', 12, 3);

Con questo codice è possibile rimuovere i campi che si desidera il JSON. Usando rest_prepare} _ {$ post_type decidi di aver eliminato tutti i campi post_type, quindi ha influenzato solo il post_type che vuoi e non tutto.

Problemi correlati