Я пытаюсь сгенерировать результаты API с помощью restful API, используя значение mata страницы для генерации данных и вызывая их обратно на страницу с помощью javascript. Возможно ли это?
Вот скрипт, который я использую. С ручными значениями в файле function.php это работает, но попытка использовать метастраницу для получения результатов не работает.
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 ... ={$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 страницы
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));
Подробнее здесь: https://stackoverflow.com/questions/758 ... to-page-wi
Мета-значение страницы Wordpress для function.php > результаты restful API возвращаются на страницу с javascript ⇐ Php
Кемеровские программисты php общаются здесь
1731310470
Anonymous
Я пытаюсь сгенерировать результаты API с помощью restful API, используя значение mata страницы для генерации данных и вызывая их обратно на страницу с помощью javascript. Возможно ли это?
Вот скрипт, который я использую. С ручными значениями в файле function.php это работает, но попытка использовать метастраницу для получения результатов не работает.
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',
) );
} );
Javascript страницы
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));
Подробнее здесь: [url]https://stackoverflow.com/questions/75867152/wordpress-page-meta-value-to-functions-php-restful-api-results-back-to-page-wi[/url]
Ответить
1 сообщение
• Страница 1 из 1
Перейти
- Кемерово-IT
- ↳ Javascript
- ↳ C#
- ↳ JAVA
- ↳ Elasticsearch aggregation
- ↳ Python
- ↳ Php
- ↳ Android
- ↳ Html
- ↳ Jquery
- ↳ C++
- ↳ IOS
- ↳ CSS
- ↳ Excel
- ↳ Linux
- ↳ Apache
- ↳ MySql
- Детский мир
- Для души
- ↳ Музыкальные инструменты даром
- ↳ Печатная продукция даром
- Внешняя красота и здоровье
- ↳ Одежда и обувь для взрослых даром
- ↳ Товары для здоровья
- ↳ Физкультура и спорт
- Техника - даром!
- ↳ Автомобилистам
- ↳ Компьютерная техника
- ↳ Плиты: газовые и электрические
- ↳ Холодильники
- ↳ Стиральные машины
- ↳ Телевизоры
- ↳ Телефоны, смартфоны, плашеты
- ↳ Швейные машинки
- ↳ Прочая электроника и техника
- ↳ Фототехника
- Ремонт и интерьер
- ↳ Стройматериалы, инструмент
- ↳ Мебель и предметы интерьера даром
- ↳ Cантехника
- Другие темы
- ↳ Разное даром
- ↳ Давай меняться!
- ↳ Отдам\возьму за копеечку
- ↳ Работа и подработка в Кемерове
- ↳ Давай с тобой поговорим...
Мобильная версия