add endpoints
This commit is contained in:
93
api/newstop.php
Normal file
93
api/newstop.php
Normal file
@@ -0,0 +1,93 @@
|
||||
<?php
|
||||
|
||||
add_action('rest_api_init', function () {
|
||||
|
||||
register_rest_route('my/v1', '/news-top', [
|
||||
'methods' => WP_REST_Server::READABLE,
|
||||
'callback' => 'my_api_news_top',
|
||||
'permission_callback' => '__return_true', // при необходимости замените на проверку доступа
|
||||
'args' => [
|
||||
'per_page' => [
|
||||
'required' => false,
|
||||
'default' => 20,
|
||||
'sanitize_callback' => 'absint',
|
||||
],
|
||||
],
|
||||
]);
|
||||
|
||||
});
|
||||
|
||||
function my_api_news_top(WP_REST_Request $request) {
|
||||
|
||||
$per_page = (int) $request->get_param('per_page');
|
||||
if ($per_page <= 0) {
|
||||
$per_page = 20;
|
||||
}
|
||||
if ($per_page > 100) {
|
||||
$per_page = 100; // защита от слишком тяжелых запросов
|
||||
}
|
||||
|
||||
// 1) news_query
|
||||
$news_query = new WP_Query([
|
||||
'post_type' => ['anew', 'yellow'],
|
||||
'ignore_sticky_posts' => true,
|
||||
'posts_per_page' => $per_page,
|
||||
'order' => 'DESC',
|
||||
'orderby' => 'post_date',
|
||||
]);
|
||||
|
||||
// 2) top_query (ids берём из опции ppp_options)
|
||||
$top_raw = get_option('ppp_options');
|
||||
$top = json_decode($top_raw);
|
||||
|
||||
$ids = [];
|
||||
if (is_array($top)) {
|
||||
$ids = array_values(array_filter(array_map(static function ($item) {
|
||||
return isset($item->id) ? absint($item->id) : 0;
|
||||
}, $top)));
|
||||
}
|
||||
|
||||
$top_query = null;
|
||||
$top_items = [];
|
||||
|
||||
if (!empty($ids)) {
|
||||
$top_query = new WP_Query([
|
||||
'post_type' => ['anew', 'yellow'],
|
||||
'ignore_sticky_posts' => true,
|
||||
'post__in' => $ids,
|
||||
'posts_per_page' => -1,
|
||||
'order' => 'DESC',
|
||||
'orderby' => 'post_date',
|
||||
]);
|
||||
|
||||
$top_items = array_map('my_api_map_post', $top_query->posts);
|
||||
}
|
||||
|
||||
$news_items = array_map('my_api_map_post', $news_query->posts);
|
||||
|
||||
return rest_ensure_response([
|
||||
'news' => [
|
||||
'found' => (int) $news_query->found_posts,
|
||||
'items' => $news_items,
|
||||
],
|
||||
'top' => [
|
||||
'ids' => $ids,
|
||||
'found' => $top_query ? (int) $top_query->found_posts : 0,
|
||||
'items' => $top_items,
|
||||
],
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Приводим WP_Post к простому массиву.
|
||||
*/
|
||||
function my_api_map_post($post) {
|
||||
return [
|
||||
'id' => (int) $post->ID,
|
||||
'type' => $post->post_type,
|
||||
'title' => get_the_title($post),
|
||||
'date' => get_the_date('c', $post),
|
||||
'uri' => wp_parse_url(get_permalink($post), PHP_URL_PATH),
|
||||
'link' => get_permalink($post),
|
||||
];
|
||||
}
|
||||
Reference in New Issue
Block a user