Skip to content

Instantly share code, notes, and snippets.

@yuriitaran
Last active November 12, 2018 00:16
Show Gist options
  • Save yuriitaran/73eca27c4df4b262b2b72a6f8ba68cb7 to your computer and use it in GitHub Desktop.
Save yuriitaran/73eca27c4df4b262b2b72a6f8ba68cb7 to your computer and use it in GitHub Desktop.
Retrieving data from Wordpress REST API
wp_enqueue_script( 'wp-rest', get_template_directory_uri() . '/js/wp-rest.js', null, null, true );
// Posts custom fields
function prepare_rest($data, $post, $request){
$_data = $data->data;
$_data['custom_fields'] = get_post_meta($post->ID); // retrieving all post meta fields
return $_data;
}
add_filter('rest_prepare_post', 'prepare_rest', 10, 3);
// CPT custom fields
function create_api_posts_meta_field() {
// register_rest_field ( 'name-of-post-type', 'name-of-field-to-return', array-of-callbacks-and-schema() )
register_rest_field( 'air_tickets', 'post-meta-fields', array(
'get_callback' => 'get_post_meta_for_api',
'schema' => null,
)
);
}
function get_post_meta_for_api( $object ) {
//get the id of the post object array
$post_id = $object['id'];
//return the post meta
return get_post_meta( $post_id );
}
add_action( 'rest_api_init', 'create_api_posts_meta_field' );
// set params
const params = {
'per_page': '100',
'order': 'asc'
};
// convert params to string
const apiParams = (function() {
let res = '', i = 0;
for (key in params) {
let sep = i === 0 ? '?' : '&';
res += sep + key + '=' + params[key];
i++
}
return res;
}());
const apiURL = '/wp-json/wp/v2/';
(function() {
// retrieving data through fetch API (not for dummy browsers)
return fetch( apiURL + 'posts' + apiParams )
.then( response => {
if ( response.status !== 200 ) {
throw new Error( 'Problem! Status Code: ' + response.status );
}
response.json().then( data => {
console.log(data) // put you callback instead this line
})
})
.catch(function(err) {
console.log( 'Error: ', err )
})
}());
(function() {
// retrieving data through HTTP request
const request = new XMLHttpRequest();
request.open('GET', apiURL + 'posts' + apiParams, true);
request.onload = function () {
if (request.status !== 200) {
console.log('Problem! Status Code: ' + request.status);
} else {
const data = JSON.parse(this.response);
console.log(data); // put you callback instead this line
}
}
request.send();
}());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment