Как получить страницу API в виде нумерации страниц в интерфейсе WordPressPhp

Кемеровские программисты php общаются здесь
Ответить
Anonymous
 Как получить страницу API в виде нумерации страниц в интерфейсе WordPress

Сообщение Anonymous »

Я подключил API, у которого есть страница, параметр Posts_per_page в теле результата, он также имеет «total»: 500, «total_pages»: 5, «current_page»: 1
API имеет значение post_per_page по умолчанию равно 100.
Настройка страницы API:

Код: Выделить всё

  $paged = absint($request->get_param('page')) ?: 1;
$posts_per_page = absint($request->get_param('posts_per_page')) ?: 100;
$posts_per_page = min($posts_per_page, 500);
//query
$args = array(
'post_type' => 'posts',
'posts_per_page' => $posts_per_page,
'paged' => $paged,
'tax_query' => array(
'relation' => 'AND',etc............
Если в Postman я запрашиваю URL-адрес как xxx.data?posts_per_page=10&page=2, результаты работают нормально.
Я хочу показать данные в интерфейсе WordPress.
Когда я подключил API, он показывает 100 сообщений на странице. поэтому я планирую указать нумерацию страниц, чтобы увидеть другие страницы, и использовал приведенный ниже код

Код: Выделить всё

// Initialize cURL
$curl = curl_init();

// Get the current page from the query string (defaults to page 1 if not set)
$page = isset($_GET['page']) ? (int) $_GET['page'] : 1;
$posts_per_page = isset($_GET['posts_per_page']) ? (int) $_GET['posts_per_page'] : 10; // Default to 10 posts per page

// Construct the API URL with dynamic page and posts_per_page parameters
$api_url = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxdata?' .
http_build_query([
'page' => $page,                  // Page parameter for filtering
'posts_per_page' => $posts_per_page  // Number of posts per page
]);

// Initialize cURL with API request
curl_setopt_array($curl, array(
CURLOPT_URL => $api_url,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => '',
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 0,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => 'GET',
CURLOPT_HTTPHEADER => array(
'Authorization: // Replace with your actual token
),
));

// Execute cURL and get the response
$response = curl_exec($curl);

// Close cURL connection
curl_close($curl);

// Decode the response (assumed JSON)
$data = json_decode($response, true);

// Check if the response contains posts
if ($data) {
// Extract pagination info from the response
$total_posts = isset($data['total']) ? $data['total'] : 0;
$total_pages = isset($data['total_pages']) ? $data['total_pages'] : 0;
$current_page = isset($data['current_page']) ? $data['current_page'] : 1;

// Display the posts







[url=">Previous[/url]





[b][/b] 

[url=">[/url]





[url=">Next[/url]



Error fetching data or no data available.


Подробнее здесь: [url]https://stackoverflow.com/questions/79192716/how-to-get-the-api-page-as-a-pagination-in-wordpress-frontend[/url]
Ответить

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

Вернуться в «Php»