Come eseguire una meta query utilizzando REST-API in WordPress 4.7+?

30 giu 2017, 15:11:24
Visualizzazioni: 35.6K
Voti: 18

Sto cercando di filtrare tramite una meta query ma non riesco a farla funzionare, qualsiasi cosa provi.

In pratica, voglio eseguire questa query attraverso la REST API:

wp-json/wp/v2/books?meta_query[relation]=OR&meta_query[0][key]=arkivera&meta_query[0][value]=1&meta_query[0][compare]==

Ho provato diversi campi personalizzati ma continua a restituire tutti gli oggetti post.

Nel mio file functions.php ho aggiunto:

function api_allow_meta_query( $valid_vars ) {
    // Unisce l'array esistente con la meta_query
    $valid_vars = array_merge( $valid_vars, array( 'meta_query') );
    return $valid_vars;
}
add_filter( 'rest_query_vars', 'api_allow_meta_query' );

Ho cercato di consultare la documentazione a riguardo ma senza successo, inoltre la maggior parte delle domande simili non sono per WordPress 4.7 poiché filter[xxx] è stato rimosso.

1
Commenti

Possibile duplicato di Filtrare più campi personalizzati con WP REST API 2

bueltge bueltge
2 gen 2018 15:05:34
Tutte le risposte alla domanda 3
2
21

Utilizza il filtro rest_{CUSTOM_POST_TYPE}_query per aggiungere il supporto ai post meta nell'API REST di WordPress per qualsiasi tipo di post.

Consulta il Gist cerca post per post meta con l'API REST.

Come si usa?

http://example.org/wp-json/wp/v2/post?meta_key=<my_meta_key>&meta_value=<my_meta_value>

Esempio

Ottieni i post il cui post meta already-visited ha valore true.

http://example.org/wp-json/wp/v2/post?meta_key=already-visited&meta_value=true

Elenca SOLO i post il cui post meta key already-visited ha valore true.

Per riferimento Cerca post per post meta con l'API REST.

Filtri Disponibili

  • rest_post_query
  • rest_page_query
  • rest_attachment_query
5 giu 2018 13:59:21
Commenti

Grazie per questo! Penso che questa dovrebbe essere la risposta accettata, credo.

jagershark jagershark
1 ott 2018 21:04:29

e per quanto riguarda le stringhe se vogliamo un campo con un valore (non nullo) posso recuperare i campi di latitudine che sono maggiori di un valore filter[meta_key]=latitude&filter[meta_compare]=%3C&filter[meta_value]=34.7 ma ho bisogno di un altro campo stringa quindi voglio ottenere quelli che hanno valore

saber tabatabaee yazdi saber tabatabaee yazdi
20 feb 2019 16:28:31
1
12

Puoi scrivere il tuo gestore REST per query personalizzate se lo desideri. Nel tuo caso, la query può essere eseguita in questo modo:

// Registra una route REST
add_action( 'rest_api_init', function () {
    // Percorso per la route di meta query
    register_rest_route( 'tchernitchenko/v2', '/my_meta_query/', array(
            'methods' => 'GET', 
            'callback' => 'custom_meta_query' 
    ) );
});

// Esegui la query effettiva e restituisci i dati
function custom_meta_query(){
    if(isset($_GET['meta_query'])) {
        $query = $_GET['meta_query'];
        // Imposta gli argomenti basati sui nostri parametri GET
        $args = array (
            'relation' => $query[0]['relation'],
            array(
                'key' => $query[0]['key'],
                'value' => $query[0]['value'],
                'compare' => '=',
            ),
        );
        // Esegui una query personalizzata
        $meta_query = new WP_Query($args);
        if($meta_query->have_posts()) {
            // Definisci un array vuoto
            $data = array();
            // Memorizza il titolo di ogni post nell'array
            while($meta_query->have_posts()) {
                $meta_query->the_post();
                $data[] =  get_the_title();
            }
            // Restituisci i dati
            return $data;
        } else {
            // Se non ci sono post
            return 'Nessun post da mostrare';
        }
    }
}

Ora, tutto ciò che devi fare è accedere a:

wp-json/tchernitchenko/v2/my_meta_query?meta_query[relation]=OR&meta_query[0][key]=arkivera&meta_query[0][value]=1&meta_query[0][compare]==
30 giu 2017 16:34:42
Commenti

Esiste un modo per estendere questo all'API Legacy di WooCommerce?

Amjad Amjad
16 gen 2021 01:49:41
9

Il seguente codice aggiunge la capacità di eseguire query multiple sui meta a tutti i tuoi tipi di post. Supporta CPT (Custom Post Type) e ACF (Advanced Custom Field). Il codice sorgente è disponibile anche su Github.

Aggiungilo al tuo file function.php

add_action( 'rest_api_init', 'wp_rest_filter_add_filters' );
 /**
  * Aggiunge i filtri necessari a ogni tipo di post
  **/
function wp_rest_filter_add_filters() {
    foreach ( get_post_types( array( 'show_in_rest' => true ), 'objects' ) as $post_type ) {
        add_filter( 'rest_' . $post_type->name . '_query', 'wp_rest_filter_add_filter_param', 10, 2 );
    }
}
/**
 * Aggiunge il parametro filter
 *
 * @param  array           $args    Gli argomenti della query.
 * @param  WP_REST_Request $request Dettagli completi sulla richiesta.
 * @return array $args.
 **/
function wp_rest_filter_add_filter_param( $args, $request ) {
    // Esci se non è impostato alcun parametro filter.
    if ( empty( $request['filter'] ) || ! is_array( $request['filter'] ) {
        return $args;
    }
    $filter = $request['filter'];
    if ( isset( $filter['posts_per_page'] ) && ( (int) $filter['posts_per_page'] >= 1 && (int) $filter['posts_per_page'] <= 100 ) ) {
        $args['posts_per_page'] = $filter['posts_per_page'];
    }
    global $wp;
    $vars = apply_filters( 'rest_query_vars', $wp->public_query_vars );
    function allow_meta_query( $valid_vars )
    {
        $valid_vars = array_merge( $valid_vars, array( 'meta_query', 'meta_key', 'meta_value', 'meta_compare' ) );
        return $valid_vars;
    }
    $vars = allow_meta_query( $vars );

    foreach ( $vars as $var ) {
        if ( isset( $filter[ $var ] ) ) {
            $args[ $var ] = $filter[ $var ];
        }
    }
    return $args;
}

IMHO, un modo migliore sarebbe includere la funzione aggiuntiva come plugin separato. Così, anche quando l'utente cambia tema, le tue chiamate API non saranno influenzate.

Per questo ho sviluppato un plugin per le meta query in WordPress. Ancora meglio, supporta anche ACF!

WP REST Filter

Dopo l'installazione, esegui una richiesta GET nel seguente formato.

https://domain.com/wp-json/acf/v3/customposttype?filter[meta_key]=acfkey&filter[meta_value]=acfvalue

Scopri il codice sorgente del plugin su Github.

24 gen 2018 22:58:04
Commenti

Ottimo plugin, però l'ordinamento per data non funziona con i campi data di ACF!

Advena Advena
30 apr 2018 13:43:05

Ciao Tanckom. Grazie per il tuo messaggio. Potresti per favore approfondire il tuo problema? Cosa hai provato? Per favore, segnala il tuo problema su https://wordpress.org/support/plugin/wp-rest-filter. Il nostro team di supporto ti risponderà lì. Grazie.

Jack Song Jack Song
30 apr 2018 20:43:29

Ciao Jack, Ho scoperto che l'URL corretto per ottenere la data dal campo ACF e ordinarla in ordine crescente o decrescente è il seguente: https://domain.com/wp-json/wp/v2/events?filter[meta_key].acf=evt_date&per_page=100&filter[order]=asc

Advena Advena
30 apr 2018 23:49:44

Fantastico! Siamo felici che il nostro plugin ti sia stato utile! :D

Jack Song Jack Song
1 mag 2018 06:53:08

Davvero, continuate così! :)

Advena Advena
1 mag 2018 13:21:13

Una sola domanda, come potrei filtrare per date in questo formato "2018-09-25 19:30:00 GMT+02:00". Date and Time picker per ACF non permette il formato ISO :( Ho provato questo ma senza successo domain.com/wp-json/wp/v2/events?filter[meta_key].acf=date&[meta_value]=2018-09-25

Advena Advena
1 mag 2018 19:50:08

Converti in ora GMT, yyyy-mm-dd'T'HH:mm:ss , poi domain.com/wp-json/wp/v2/events?filter[meta_key]=date&[meta_value]=2018-09-25T23:59:59. Credo che ACF salvi i dati in formato IOS nel MySQL, quindi dovrebbe funzionare.

Jack Song Jack Song
2 mag 2018 05:12:42

Sfortunatamente, è impossibile ottenere la Data e l'Ora senza spazi con il plugin Add-on per ACF "Date and Time Picker" :/ Ecco perché ho dovuto fare in questo modo.

Advena Advena
2 mag 2018 18:20:08

Possiamo aiutarti con questo. Per favore inviaci un'email con i dettagli del problema a hi@sk8.tech. Ti risponderemo il prima possibile.

Jack Song Jack Song
3 mag 2018 00:55:13
Mostra i restanti 4 commenti