我正在尝试使用restful API生成API结果,同时使用页面mata值生成数据并使用javascript将其回调回页面。这可能吗?
这是我正在使用的脚本。使用functions.php中的手动值,它可以工作,但尝试使用页面元来生成结果,它不会工作。
函数.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',
) );
} );
页面 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>
您应该将需要元数据的页面 ID 传递给其余 API。 REST API 不知道浏览器页面。
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;
...
}