add endpoints

This commit is contained in:
Profile Profile
2026-02-15 23:06:39 +03:00
parent 141d117b96
commit 485913ca23
4 changed files with 179 additions and 23 deletions

93
api/newstop.php Normal file
View 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),
];
}

View File

@@ -13,11 +13,9 @@ require 'inc/article-rss-feed.php'; //rss ленты статей по дата
require "inc/meta_keywords.php";
require "inc/journal_issue.php"; //номера журналов
require "inc/rank-description.php"; //подменяем дескрипшт от соцсетей
require "inc/graphql.php"; //graphql
require "inc/replace_old_copyright.php"; //подменяем фото для старых картинок с "плохим" копирайтом
//scheduler
@@ -31,15 +29,17 @@ if ( defined( 'WP_CLI' ) && WP_CLI ) {
include "inc/get_cached_alm.php";
if (is_admin()) {
require "inc/add_adv_checked.php"; // рекламная статья
require "inc/admin/auto_check.php"; // помечакм не отправлять в Дзен
require "inc/admin/lock-terms.php"; // banned и keys
require "inc/admin/coauthors_filter.php"; //поиск по соавторам
require "inc/admin/coauthors_filter.php"; // фильтры авторов
}
#api
require "api/newstop.php"; // управление REST API
//TODO: Убрать все эти is_yn, is_zen и прочее и внутри плагинов регулировать вывод
@@ -300,8 +300,9 @@ function add_article_in_main_query( $query ) {
//var_dump( get_option('layf_custom_url'));
if (is_admin()){
if (get_query_var('author_name')){
$query->set('post_type', array('profile_article','anew','yellow'));
//$query->set('post_type', array('profile_article','anew','yellow'));
//echo '<!--'.$query->request.'-->';
return $query;
}else if (filter_input(INPUT_GET,'page') == 'wps_authors_page'){
$query->set('post_type', array('profile_article','anew','yellow'));
$query->set('posts_per_page', -1);

View File

@@ -1,5 +1,4 @@
<?php
// Убираем стандартный фильтр авторов для profile_article
add_action('admin_head-edit.php', 'cap_hide_default_author_filter');
function cap_hide_default_author_filter() {
@@ -71,6 +70,9 @@ function cap_filter_by_coauthor($post_type) {
// Обертка для фильтра и кнопки
echo '<div id="author-filter-wrapper">';
// Добавляем скрытое поле для сохранения post_type
echo '<input type="hidden" name="post_type" value="profile_article">';
echo '<select name="author_name" id="author_name_filter">';
echo '<option value="">Все авторы</option>';
@@ -107,22 +109,55 @@ function cap_filter_by_coauthor($post_type) {
}
// Модифицируем запрос для фильтрации
add_filter('parse_query', 'cap_filter_posts_by_coauthor');
add_filter('pre_get_posts', 'cap_filter_posts_by_coauthor', 999);
function cap_filter_posts_by_coauthor($query) {
global $pagenow, $typenow;
if (!is_admin() || $pagenow !== 'edit.php' || $typenow !== 'profile_article') {
// Проверяем, что это админка и главный запрос
if (!is_admin() || !$query->is_main_query()) {
return;
}
global $pagenow;
if ($pagenow !== 'edit.php') {
return;
}
// Получаем тип поста (может быть строкой или массивом)
$current_post_type = $query->get('post_type');
// Если массив - берем первый элемент
if (is_array($current_post_type)) {
$current_post_type = reset($current_post_type);
}
// Если пустой - берем из GET
if (empty($current_post_type) && isset($_GET['post_type'])) {
$current_post_type = is_array($_GET['post_type']) ? reset($_GET['post_type']) : $_GET['post_type'];
}
if ($current_post_type !== 'profile_article') {
return;
}
// Убираем пустой параметр s (поиск)
if (isset($_GET['s']) && (empty($_GET['s']) || $_GET['s'] === '')) {
$query->set('s', '');
unset($_GET['s']);
}
// Если выбран автор в фильтре
if (isset($_GET['author_name']) && !empty($_GET['author_name'])) {
$query->query_vars['tax_query'] = [
[
$tax_query = $query->get('tax_query');
if (!is_array($tax_query)) {
$tax_query = [];
}
$tax_query[] = [
'taxonomy' => 'author',
'field' => 'slug',
'terms' => sanitize_text_field($_GET['author_name'])
]
];
$query->set('tax_query', $tax_query);
}
}
@@ -154,24 +189,50 @@ function cap_enqueue_select2($hook) {
width: "140px"
});
// Обработка очистки
// Получаем текущий URL для сброса
var baseUrl = "' . admin_url('edit.php?post_type=profile_article') . '";
// Обработка очистки - сохраняем post_type
$select.on("select2:clear", function(e) {
$(this).val("").trigger("change");
$(this).closest("form").submit();
window.location.href = baseUrl;
});
// Функция для удаления пустых полей формы
function removeEmptyFields($form) {
$form.find("input[type=text], input[type=search]").each(function() {
if ($(this).val() === "" || $(this).val() === null) {
$(this).remove();
}
});
}
// Обработка выбора
$select.on("select2:select", function(e) {
$(this).closest("form").submit();
var $form = $(this).closest("form");
removeEmptyFields($form);
$form.submit();
});
// Enter в поиске
$(document).on("keypress", ".select2-search__field", function(e) {
if (e.which === 13) {
e.preventDefault();
$select.closest("form").submit();
var $form = $select.closest("form");
removeEmptyFields($form);
$form.submit();
}
});
// Обработка клика по кнопке Фильтр
$("#cap-filter-submit").on("click", function(e) {
var $form = $(this).closest("form");
removeEmptyFields($form);
});
// Глобальная обработка отправки формы фильтров
$("#posts-filter").on("submit", function(e) {
removeEmptyFields($(this));
});
});
');

View File

@@ -50,7 +50,8 @@
<span class="footer__delimiter"></span>
<div class="footer__copyright">
<p class="d-block d-md-flex">
Информационное агентство "Деловой журнал "Профиль" зарегистрировано в Федеральной службе по надзору в сфере связи, информационных технологий и массовых коммуникаций. Свидетельство о государственной регистрации серии ИА № ФС 77 - 89668 от 23.06.2025
Информационное агентство "Деловой журнал "Профиль" зарегистрировано в Федеральной службе по надзору в сфере связи, информационных технологий и массовых коммуникаций. Свидетельство о государственной регистрации серии ИА № ФС 77 - 89668 от 23.06.2025<br>
Cвидетельство о регистрации электронного СМИ Эл NºФС77-73069 от 09 июня 2018 г.
</p>
<p>
©<?= date("Y") ?> ИДР. Все права защищены.