I'm trying to generate API results with restful API while using page mata value to generate data and calling it back to page with javascript. Is this possible?
Here is the script I'm using. With manual values in functions.php it works, but trying to use page meta to generate results it wont work.
Functions.php
function get_flight_data() {
$api_key = '#';
$origin = get_post_meta(get_the_ID(), 'destination', true);
$destination = get_post_meta(get_the_ID(), 'origin', true);
$url = "https://api.travelpayouts.com/v2/prices/latest?currency=EUR&period=year&page=1&limit=30&origin={$origin}&destination={$destination}&token={$api_key}";
$response = wp_remote_get( $url );
if( is_wp_error( $response ) ) {
return null;
}
$body = wp_remote_retrieve_body( $response );
$data = json_decode( $body );
$result = array();
foreach ( $data->data as $flight ) {
$result[] = array(
'origin' => $flight->origin,
'destination' => $flight->destination,
'depart_date' => $flight->depart_date,
'price' => "{$flight->value} {$data->currency}",
);
}
return $result;
}
add_action( 'rest_api_init', function () {
register_rest_route( 'myplugin/v1', '/flight-data', array(
'methods' => 'GET',
'callback' => 'get_flight_data',
) );
} );
Page javascript
<script>
fetch('https://#/wp-json/myplugin/v1/flight-data')
.then(response => response.json())
.then(data => {
console.log(data);
// Create a table element to display flight information
const table = document.createElement('table');
const headerRow = table.insertRow(0);
const headerCell1 = headerRow.insertCell(0);
headerCell1.textContent = 'Origin';
const headerCell2 = headerRow.insertCell(1);
headerCell2.textContent = 'Destination';
const headerCell3 = headerRow.insertCell(2);
headerCell3.textContent = 'Departure Date';
const headerCell4 = headerRow.insertCell(3);
headerCell4.textContent = 'Price';
// Loop through the data array and add each flight to the table
data.forEach(flight => {
const row = table.insertRow(-1);
const cell1 = row.insertCell(0);
cell1.textContent = flight.origin;
const cell2 = row.insertCell(1);
cell2.textContent = flight.destination;
const cell3 = row.insertCell(2);
cell3.textContent = flight.depart_date;
const cell4 = row.insertCell(3);
cell4.textContent = flight.price;
});
// Add the table to the page
document.body.appendChild(table);
})
.catch(error => console.error(error));
</script>
You should pass the ID of the page that you want meta data from to the rest API. The REST API does not know the browser page.
add_action( 'rest_api_init', function () {
register_rest_route('myplugin/v1', 'flight-data/post/(?P<post>\d+)/', [
'methods' => 'GET',
'callback' => 'get_flight_data',
'permission_callback' => '__return_true',
]);
});
function get_flight_data($request) {
$post_id = $request['post']) ?? 0;
...
}