add files inc
This commit is contained in:
363
inc/graphql.php
Normal file
363
inc/graphql.php
Normal file
@@ -0,0 +1,363 @@
|
||||
<?php
|
||||
|
||||
// Общая функция для получения соавторов
|
||||
function get_coauthors_for_graphql($post_id) {
|
||||
if (!function_exists('get_coauthors')) {
|
||||
return [];
|
||||
}
|
||||
|
||||
$coauthors = get_coauthors($post_id);
|
||||
$users = [];
|
||||
|
||||
foreach ($coauthors as $coauthor) {
|
||||
// Пропускаем если это основной автор (он уже в поле author)
|
||||
// if ($coauthor->ID == $author_id) continue;
|
||||
|
||||
if (isset($coauthor->type) && $coauthor->type === 'guest-author') {
|
||||
// Для гостевых авторов
|
||||
$users[] = [
|
||||
'__typename' => 'GuestAuthor',
|
||||
'id' => $coauthor->user_nicename,
|
||||
'name' => $coauthor->display_name,
|
||||
'firstName' => $coauthor->first_name,
|
||||
'lastName' => $coauthor->last_name,
|
||||
'description' => $coauthor->description,
|
||||
'avatar' => get_avatar_url($coauthor->user_email, ['size' => 96]),
|
||||
'url' => get_author_posts_url($coauthor->ID, $coauthor->user_nicename),
|
||||
'type' => 'guest-author'
|
||||
];
|
||||
} else {
|
||||
// Для обычных пользователей
|
||||
$user = get_user_by('id', $coauthor->ID);
|
||||
if ($user) {
|
||||
$avatar_url = '';
|
||||
if (function_exists('get_avatar_url')) {
|
||||
$avatar_url = get_avatar_url($user->ID, ['size' => 96]);
|
||||
}
|
||||
|
||||
$users[] = [
|
||||
'__typename' => 'User',
|
||||
'id' => 'user-' . $user->ID,
|
||||
'name' => $user->display_name,
|
||||
'firstName' => $user->first_name,
|
||||
'lastName' => $user->last_name,
|
||||
'description' => $user->description,
|
||||
'avatar' => $avatar_url,
|
||||
'url' => get_author_posts_url($user->ID),
|
||||
'databaseId' => $user->ID
|
||||
];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return $users;
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
add_filter( 'register_post_type_args', function( $args, $post_type ) {
|
||||
|
||||
if ( 'profile_article' === $post_type ) {
|
||||
$args['show_in_graphql'] = true;
|
||||
$args['graphql_single_name'] = 'ProfileArticle';
|
||||
$args['graphql_plural_name'] = 'ProfileArticles';
|
||||
}
|
||||
|
||||
if ( 'anew' === $post_type ) {
|
||||
$args['show_in_graphql'] = true;
|
||||
$args['graphql_single_name'] = 'ANew'; // или 'Anew' - смотрите комментарий ниже
|
||||
$args['graphql_plural_name'] = 'ANews'; // или 'Anews' - смотрите комментарий ниже
|
||||
}
|
||||
|
||||
|
||||
return $args;
|
||||
}, 10, 2 );
|
||||
|
||||
//цвет меню
|
||||
add_action('graphql_register_types', function() {
|
||||
|
||||
// Поле цвета для пунктов меню
|
||||
register_graphql_field('MenuItem', 'menuItemColor', [
|
||||
'type' => 'String',
|
||||
'description' => __('Custom color for menu item', 'your-textdomain'),
|
||||
'resolve' => function($menu_item) {
|
||||
$color = get_post_meta($menu_item->databaseId, '_menu_item_color', true);
|
||||
return !empty($color) ? $color : null;
|
||||
}
|
||||
]);
|
||||
|
||||
// Поле цвета для категорий
|
||||
register_graphql_field( 'Category', 'color', [
|
||||
'type' => 'String',
|
||||
'description' => __( 'Background color class for category badge', 'your-textdomain' ),
|
||||
'resolve' => function( $term ) {
|
||||
$color = get_field( 'color', 'category_' . $term->term_id );
|
||||
return ! empty( $color ) ? $color : 'bg-blue';
|
||||
}
|
||||
] );
|
||||
|
||||
// Соавторы
|
||||
|
||||
$post_types_with_coauthors = ['ProfileArticle', 'ANew']; // Исправлено: ANew
|
||||
foreach ($post_types_with_coauthors as $post_type) {
|
||||
register_graphql_field($post_type, 'coauthors', [
|
||||
'type' => ['list_of' => 'User'],
|
||||
'description' => sprintf(__('Co-authors of the %s', 'your-textdomain'), $post_type),
|
||||
'resolve' => function($post_object) use ($post_type) {
|
||||
$post_id = $post_object->databaseId;
|
||||
return get_coauthors_for_graphql($post_id);
|
||||
}
|
||||
]);
|
||||
}
|
||||
|
||||
|
||||
});
|
||||
|
||||
|
||||
|
||||
//вторчиный заг
|
||||
add_action('graphql_register_types', function() {
|
||||
|
||||
// Для ProfileArticle
|
||||
register_graphql_field('ProfileArticle', 'secondaryTitle', [
|
||||
'type' => 'String',
|
||||
'description' => __('Secondary title from Secondary Title plugin', 'your-textdomain'),
|
||||
'resolve' => function($post_object) {
|
||||
$post_id = $post_object->databaseId;
|
||||
|
||||
// Прямое получение поля, которое использует плагин
|
||||
$secondary_title = get_post_meta($post_id, 'secondary_post_title', true);
|
||||
|
||||
// Если пусто, проверяем через функцию плагина (если она существует)
|
||||
if (empty($secondary_title) && function_exists('get_secondary_title')) {
|
||||
$secondary_title = get_secondary_title($post_id);
|
||||
}
|
||||
|
||||
return !empty($secondary_title) ? $secondary_title : null;
|
||||
}
|
||||
]);
|
||||
|
||||
// Для Anews
|
||||
register_graphql_field('Anews', 'secondaryTitle', [
|
||||
'type' => 'String',
|
||||
'description' => __('Secondary title from Secondary Title plugin', 'your-textdomain'),
|
||||
'resolve' => function($post_object) {
|
||||
$post_id = $post_object->databaseId;
|
||||
|
||||
$secondary_title = get_post_meta($post_id, 'secondary_post_title', true);
|
||||
|
||||
if (empty($secondary_title) && function_exists('get_secondary_title')) {
|
||||
$secondary_title = get_secondary_title($post_id);
|
||||
}
|
||||
|
||||
return !empty($secondary_title) ? $secondary_title : null;
|
||||
}
|
||||
]);
|
||||
});
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Регистрация colonItem для ACF Checkbox
|
||||
*/
|
||||
add_action('graphql_register_types', function() {
|
||||
|
||||
// Регистрируем поле как Boolean
|
||||
register_graphql_field('ProfileArticle', 'colonItem', [
|
||||
'type' => 'Boolean',
|
||||
'description' => 'Флаг поста колонки',
|
||||
'resolve' => function($post) {
|
||||
$value = get_field('colon_item', $post->ID);
|
||||
|
||||
// ACF Checkbox возвращает массив или false
|
||||
// Если checkbox отмечен, get_field вернет массив: ['true']
|
||||
// Если не отмечен - false или пустой массив
|
||||
|
||||
if (is_array($value) && in_array('true', $value)) {
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
]);
|
||||
|
||||
// Для типа Anew (если нужно)
|
||||
register_graphql_field('Anew', 'colonItem', [
|
||||
'type' => 'Boolean',
|
||||
'description' => 'Флаг поста колонки',
|
||||
'resolve' => function($post) {
|
||||
$value = get_field('colon_item', $post->ID);
|
||||
|
||||
if (is_array($value) && in_array('true', $value)) {
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
]);
|
||||
|
||||
// Регистрируем where аргумент
|
||||
register_graphql_field('RootQueryToProfileArticleConnectionWhereArgs', 'colonItemEquals', [
|
||||
'type' => 'Boolean',
|
||||
'description' => 'Фильтровать по полю colonItem',
|
||||
]);
|
||||
|
||||
// Для Anew
|
||||
register_graphql_field('RootQueryToAnewConnectionWhereArgs', 'colonItemEquals', [
|
||||
'type' => 'Boolean',
|
||||
'description' => 'Фильтровать по полю colonItem',
|
||||
]);
|
||||
});
|
||||
|
||||
/**
|
||||
* Фильтрация для ACF Checkbox
|
||||
*/
|
||||
add_filter('graphql_post_object_connection_query_args', function($query_args, $source, $args, $context, $info) {
|
||||
|
||||
if (isset($args['where']['colonItemEquals'])) {
|
||||
$colon_value = $args['where']['colonItemEquals'];
|
||||
|
||||
if (!isset($query_args['meta_query'])) {
|
||||
$query_args['meta_query'] = [];
|
||||
}
|
||||
|
||||
if ($colon_value === true) {
|
||||
// Для ACF Checkbox используем LIKE с сериализованным значением
|
||||
$query_args['meta_query'][] = [
|
||||
'key' => 'colon_item',
|
||||
'value' => '"true"', // Ищем "true" внутри сериализованного массива
|
||||
'compare' => 'LIKE'
|
||||
];
|
||||
} else {
|
||||
// Ищем посты без этого значения
|
||||
$query_args['meta_query'][] = [
|
||||
'relation' => 'OR',
|
||||
[
|
||||
'key' => 'colon_item',
|
||||
'value' => '"true"',
|
||||
'compare' => 'NOT LIKE'
|
||||
],
|
||||
[
|
||||
'key' => 'colon_item',
|
||||
'compare' => 'NOT EXISTS'
|
||||
]
|
||||
];
|
||||
}
|
||||
}
|
||||
|
||||
return $query_args;
|
||||
}, 10, 5);
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Добавление поддержки фильтрации по mainItem для ProfileArticle
|
||||
*/
|
||||
add_action('graphql_register_types', function() {
|
||||
|
||||
// Регистрируем ACF поле mainItem в GraphQL
|
||||
register_graphql_field('ProfileArticle', 'mainItem', [
|
||||
'type' => 'Boolean',
|
||||
'description' => 'Флаг главного поста',
|
||||
'resolve' => function($post) {
|
||||
$value = get_field('main_item', $post->ID);
|
||||
|
||||
// ACF Checkbox возвращает массив или false
|
||||
// Если checkbox отмечен, get_field вернет массив: ['true']
|
||||
// Если не отмечен - false или пустой массив
|
||||
|
||||
if (is_array($value) && in_array('true', $value)) {
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
]);
|
||||
|
||||
// Регистрируем кастомный where аргумент для ProfileArticle
|
||||
register_graphql_field('RootQueryToProfileArticleConnectionWhereArgs', 'mainItemEquals', [
|
||||
'type' => 'Boolean',
|
||||
'description' => 'Фильтровать статьи профиля по полю mainItem',
|
||||
]);
|
||||
});
|
||||
|
||||
/**
|
||||
* Применяем фильтрацию через meta_query для mainItem
|
||||
*/
|
||||
add_filter('graphql_post_object_connection_query_args', function($query_args, $source, $args, $context, $info) {
|
||||
|
||||
// Проверяем наличие аргумента mainItemEquals
|
||||
if (isset($args['where']['mainItemEquals'])) {
|
||||
$main_value = $args['where']['mainItemEquals'];
|
||||
|
||||
if (!isset($query_args['meta_query'])) {
|
||||
$query_args['meta_query'] = [];
|
||||
}
|
||||
|
||||
if ($main_value === true) {
|
||||
// Для ACF Checkbox используем LIKE с сериализованным значением
|
||||
$query_args['meta_query'][] = [
|
||||
'key' => 'main_item',
|
||||
'value' => '"true"', // Ищем "true" внутри сериализованного массива
|
||||
'compare' => 'LIKE'
|
||||
];
|
||||
} else {
|
||||
// Ищем посты без этого значения
|
||||
$query_args['meta_query'][] = [
|
||||
'relation' => 'OR',
|
||||
[
|
||||
'key' => 'main_item',
|
||||
'value' => '"true"',
|
||||
'compare' => 'NOT LIKE'
|
||||
],
|
||||
[
|
||||
'key' => 'main_item',
|
||||
'compare' => 'NOT EXISTS'
|
||||
]
|
||||
];
|
||||
}
|
||||
}
|
||||
|
||||
return $query_args;
|
||||
}, 10, 5);
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
// авторы
|
||||
add_action('graphql_register_types', function() {
|
||||
// Добавляем аргумент coauthorLogin
|
||||
register_graphql_field('RootQueryToContentNodeConnectionWhereArgs', 'coauthorLogin', [
|
||||
'type' => 'String',
|
||||
'description' => __('Filter by coauthor login (nicename)', 'textdomain'),
|
||||
]);
|
||||
});
|
||||
|
||||
add_filter('graphql_post_object_connection_query_args', function($query_args, $source, $args, $context, $info) {
|
||||
// Фильтр по логину
|
||||
if (isset($args['where']['coauthorLogin']) && !empty($args['where']['coauthorLogin'])) {
|
||||
$login = sanitize_user($args['where']['coauthorLogin']);
|
||||
|
||||
// Находим пользователя по логину
|
||||
$user = get_user_by('login', $login);
|
||||
if ($user) {
|
||||
$query_args['author'] = $user->ID;
|
||||
}
|
||||
}
|
||||
|
||||
// Фильтр по имени (если нужен)
|
||||
if (isset($args['where']['coauthorName']) && !empty($args['where']['coauthorName'])) {
|
||||
$query_args['author_name'] = sanitize_title($args['where']['coauthorName']);
|
||||
}
|
||||
|
||||
return $query_args;
|
||||
}, 10, 5);
|
||||
Reference in New Issue
Block a user