Dekart Deploy Bot f74fdf6eab GLOBAL
2026-10-23 22:44:11 +00:00

1831 lines
61 KiB
PHP
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

<?php
defined('ABSPATH') || exit;
add_filter('wpseo_json_ld_output', '__return_false');
// единственный ld+json на страницу: собираем все блоки в один @graph
add_action('template_redirect', 'dekart_jsonld_dedupe_start', 1);
function dekart_jsonld_dedupe_start(): void
{
if (is_admin() || is_feed() || is_robots() || is_404() || (defined('REST_REQUEST') && REST_REQUEST)) {
return;
}
ob_start('dekart_jsonld_dedupe');
}
function dekart_jsonld_dedupe(string $html): string
{
if (stripos($html, 'application/ld+json') === false) {
return $html;
}
$re = '#<script\b[^>]*type=("|\')application/ld\+json\1[^>]*>(.*?)</script>#is';
if (! preg_match_all($re, $html, $matches, PREG_SET_ORDER) || count($matches) < 2) {
return $html;
}
$context = 'https://schema.org';
$graph = array();
$seen = array();
$valid = array();
foreach ($matches as $i => $m) {
$json = json_decode(trim($m[2]), true);
if (! is_array($json)) {
continue;
}
$valid[] = $i;
if (! empty($json['@context'])) {
$context = $json['@context'];
}
$entities = (isset($json['@graph']) && is_array($json['@graph'])) ? $json['@graph'] : array( $json );
foreach ($entities as $entity) {
if (! is_array($entity)) {
continue;
}
$id = $entity['@id'] ?? '';
if (is_string($id) && $id !== '') {
if (isset($seen[$id])) {
continue;
}
$seen[$id] = true;
}
$graph[] = $entity;
}
}
if (count($valid) < 2 || empty($graph)) {
return $html;
}
$merged = '<script type="application/ld+json">' . "\n"
. wp_json_encode(array( '@context' => $context, '@graph' => $graph ), JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_HEX_TAG)
. "\n" . '</script>';
$first = $valid[0];
$idx = 0;
return preg_replace_callback($re, function ($m) use (&$idx, $first, $valid, $merged) {
$cur = $idx++;
if ($cur === $first) {
return $merged;
}
return in_array($cur, $valid, true) ? '' : $m[0];
}, $html);
}
add_filter('wpseo_opengraph_type', 'dekart_schema_og_type', 10, 1);
function dekart_schema_og_type(string $type): string
{
if (is_page_template('page-podgotovka-k-shkole.php') || is_page_template('page-camp.php')) {
return 'website';
}
return $type;
}
add_filter('wpseo_frontend_presenter_classes', function (array $presenters): array {
if (! is_page_template('page-podgotovka-k-shkole.php')) {
return $presenters;
}
$presenters = array_filter($presenters, function (string $p): bool {
return strpos($p, 'Article_Modified_Time') === false
&& strpos($p, 'Article_Published_Time') === false
&& strpos($p, 'Article_Author') === false
&& strpos($p, 'Article_Publisher') === false
&& strpos($p, 'Label1') === false
&& strpos($p, 'Data1') === false;
});
return $presenters;
});
add_action('wp_head', 'dekart_schema_output', 1);
function dekart_schema_page_url(): string
{
$id = get_the_ID();
return $id ? get_permalink($id) : home_url('/');
}
function dekart_schema_output(): void
{
if (! is_page_template('page-podgotovka-k-shkole.php')) {
return;
}
if (! function_exists('carbon_get_post_meta') || ! function_exists('carbon_get_theme_option')) {
return;
}
$cache_key = 'dekart_schema_graph_' . get_the_ID() . '_' . determine_locale();
$cached = wp_cache_get($cache_key, 'dekart_schema');
if (false !== $cached) {
echo $cached;
return;
}
$graph = array();
$webpage = dekart_schema_webpage();
if ($webpage) {
$graph[] = $webpage;
}
$website = dekart_schema_website();
if ($website) {
$graph[] = $website;
}
$breadcrumb = dekart_schema_breadcrumb();
if ($breadcrumb) {
$graph[] = $breadcrumb;
}
$organization = dekart_schema_organization();
if ($organization) {
$graph[] = $organization;
}
$local_business = dekart_schema_local_business();
if ($local_business) {
$graph[] = $local_business;
}
$course = dekart_schema_course();
if ($course) {
$graph[] = $course;
}
// абонементы уже внутри Course, дубли не выводим
$course_offer_ids = array();
if (! empty($course['offers']) && is_array($course['offers'])) {
foreach ($course['offers'] as $course_offer) {
if (! empty($course_offer['@id'])) {
$course_offer_ids[$course_offer['@id']] = true;
}
}
}
$offers = dekart_schema_offer();
if (! empty($offers)) {
if (isset($offers[0]) && is_array($offers[0])) {
foreach ($offers as $offer) {
if (! empty($offer['@id']) && isset($course_offer_ids[$offer['@id']])) {
continue;
}
$graph[] = $offer;
}
} else {
$graph[] = $offers;
}
}
$rating = dekart_schema_rating();
if ($rating) {
$graph[] = $rating;
}
$service = dekart_schema_service();
if ($service) {
$graph[] = $service;
}
$faq = dekart_schema_faq();
if ($faq) {
$graph[] = $faq;
}
$event = dekart_schema_trial_event();
if ($event) {
$graph[] = $event;
}
$reviews = dekart_schema_reviews();
if (! empty($reviews) && is_array($reviews)) {
$graph[] = array(
'@type' => 'ItemList',
'@id' => dekart_schema_page_url() . '#reviews',
'name' => 'Отзывы о подготовке к школе',
'description' => 'Отзывы родителей о курсе подготовки к школе',
'itemListElement' => array_map(function ($review, $index) {
return array(
'@type' => 'ListItem',
'position' => $index + 1,
'item' => $review,
);
}, $reviews, array_keys($reviews)),
'numberOfItems' => count($reviews),
);
}
$teachers = dekart_schema_teachers();
if (! empty($teachers) && is_array($teachers)) {
foreach ($teachers as $person) {
$graph[] = $person;
}
}
$author = dekart_schema_author();
if ($author) {
$graph[] = $author;
}
if (empty($graph)) {
return;
}
$json = wp_json_encode(
array(
'@context' => 'https://schema.org',
'@graph' => $graph,
),
JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES
);
if (false === $json) {
return;
}
$output = '<script type="application/ld+json">' . "\n" . $json . "\n" . '</script>' . "\n";
wp_cache_set($cache_key, $output, 'dekart_schema', 3600);
echo $output;
}
function dekart_schema_webpage(): ?array
{
$post_id = get_the_ID();
$url = get_permalink($post_id) ?: dekart_schema_page_url();
$yoast_title = get_post_meta($post_id, '_yoast_wpseo_title', true);
$name = $yoast_title ?: wp_get_document_title();
$description = get_post_meta($post_id, '_yoast_wpseo_metadesc', true);
$description = $description ?: get_post_meta($post_id, 'rank_math_description', true);
$description = $description ?: carbon_get_post_meta($post_id, 'banner_subtitle');
$description = $description ?: 'Подготовка к школе для детей 5–7 лет' . (dekart_branch_city() !== '' ? ' в ' . dekart_branch_city() : '') . '. Чтение, письмо, математика, логика.';
$image_url = '';
if ($post_id && has_post_thumbnail($post_id)) {
$image_url = get_the_post_thumbnail_url($post_id, 'full');
}
$about_text = function_exists('dekart_fill_placeholders') ? dekart_fill_placeholders((string) carbon_get_post_meta($post_id, 'pksh_level')) : (string) carbon_get_post_meta($post_id, 'pksh_level');
if ('' === trim($about_text)) {
$about_text = 'Подготовка к школе';
}
$city = (dekart_branch_option('branch_city') ?: dekart_branch_city());
$about_name = wp_strip_all_tags($about_text);
if ('' !== $city && false === mb_stripos($about_name, $city)) {
$about_name = sprintf('%s в %s', $about_name, $city);
}
$data = Pksh_Data::instance();
$webpage = array(
'@type' => 'WebPage',
'@id' => $url . '#webpage',
'url' => $url,
'name' => wp_strip_all_tags($name),
'description' => wp_strip_all_tags($description),
'inLanguage' => str_replace('_', '-', determine_locale() ?: 'ru'),
'isPartOf' => array(
'@id' => home_url('/') . '#website',
),
'breadcrumb' => array(
'@id' => $url . '#breadcrumb',
),
'mainEntity' => array(
'@id' => $url . '#course',
),
'speakable' => array(
'@type' => 'SpeakableSpecification',
'cssSelector' => array(
'h1.ds-hero__h1',
'.ds-hero__subtitle',
),
),
'about' => array(
'@type' => 'Thing',
'name' => $about_name,
),
'keywords' => wp_strip_all_tags(
'подготовка к школе, дошкольное образование, обучение чтению, обучение письму, '
. 'математика для дошкольников, развитие логики, курсы для детей 5-7 лет, '
. $city
),
'datePublished' => $data->get_page_publish_date(),
'dateModified' => $data->get_page_modified_date(),
'author' => array(
'@id' => $url . '#author',
),
);
$faq_items = carbon_get_post_meta($post_id, 'pksh_faq_items');
if (! empty($faq_items) && is_array($faq_items)) {
$webpage['hasPart'] = array(
'@id' => $url . '#faq',
);
}
return $webpage;
}
function dekart_schema_website(): ?array
{
$site_name = (dekart_branch_option('branch_name') ?: dekart_site_name());
$home_url = home_url('/');
return array(
'@type' => 'WebSite',
'@id' => $home_url . '#website',
'url' => $home_url,
'name' => wp_strip_all_tags($site_name),
'publisher' => array(
'@id' => $home_url . '#organization',
),
'inLanguage' => str_replace('_', '-', determine_locale() ?: 'ru'),
'potentialAction' => array(
array(
'@type' => 'SearchAction',
'target' => array(
'@type' => 'EntryPoint',
'urlTemplate' => $home_url . '?s={search_term_string}',
),
'query-input' => 'required name=search_term_string',
),
),
);
}
function dekart_schema_breadcrumb(): ?array
{
$page_url = dekart_schema_page_url();
$name = carbon_get_post_meta(get_the_ID(), 'banner_h1') ?: 'Подготовка к школе';
return array(
'@type' => 'BreadcrumbList',
'@id' => $page_url . '#breadcrumb',
'itemListElement' => array(
array(
'@type' => 'ListItem',
'position' => 1,
'name' => 'Главная',
'item' => home_url('/'),
),
array(
'@type' => 'ListItem',
'position' => 2,
'name' => wp_strip_all_tags($name),
'item' => $page_url,
),
),
);
}
function dekart_schema_option(string $schema_key, string $branch_key, $default = '')
{
$val = carbon_get_theme_option($schema_key);
if (! empty($val)) {
return $val;
}
$val = get_option($branch_key);
if (! empty($val)) {
return $val;
}
return $default;
}
function dekart_branch_option(string $key, string $default = ''): string
{
$val = get_option($key);
if (! empty($val) && is_string($val)) {
return trim($val);
}
return $default;
}
function dekart_schema_organization(): ?array
{
$home_url = home_url('/');
$brand = (dekart_branch_option('branch_name') ?: dekart_site_name());
$org = array(
'@type' => 'Organization',
'@id' => $home_url . '#organization',
'name' => wp_strip_all_tags($brand),
'url' => $home_url,
'logo' => array(
'@type' => 'ImageObject',
'url' => dekart_resolve_logo(),
),
);
$legal_name = dekart_schema_option('schema_legal_name', 'branch_legal_name');
if (! empty($legal_name) && is_string($legal_name)) {
$org['legalName'] = wp_strip_all_tags(trim($legal_name));
}
$cp_phone = dekart_branch_option('branch_phone', '');
if ($cp_phone) {
$org['contactPoint'] = array(
'@type' => 'ContactPoint',
'telephone' => wp_strip_all_tags($cp_phone),
'contactType' => 'customer service',
'areaServed' => 'RU',
'availableLanguage' => 'Russian',
);
}
return $org;
}
function dekart_resolve_logo(): string
{
$branch_logo = get_option('branch_logo');
if (! empty($branch_logo)) {
if (is_array($branch_logo) && isset($branch_logo['url'])) {
return $branch_logo['url'];
}
$url = wp_get_attachment_url($branch_logo);
if ($url) {
return $url;
}
}
$banner_img = carbon_get_post_meta(get_the_ID(), 'banner_img');
if (! empty($banner_img)) {
if (is_array($banner_img) && isset($banner_img['url'])) {
return $banner_img['url'];
}
$url = wp_get_attachment_url($banner_img);
if ($url) {
return $url;
}
}
if (has_custom_logo()) {
$logo = wp_get_attachment_image_url(get_theme_mod('custom_logo'), 'full');
if ($logo) {
return $logo;
}
}
$post_id = get_the_ID();
if ($post_id && has_post_thumbnail($post_id)) {
$url = get_the_post_thumbnail_url($post_id, 'full');
if ($url) {
return $url;
}
}
return get_template_directory_uri() . '/assets/images/logo-svg.svg';
}
function dekart_schema_opening_hours(): array
{
$spec = array();
$hours_cf = carbon_get_theme_option('schema_hours');
if (! empty($hours_cf) && is_array($hours_cf)) {
foreach ($hours_cf as $entry) {
$day = isset($entry['day_of_week']) ? trim((string) $entry['day_of_week']) : '';
if ('' === $day) {
continue;
}
if (! empty($entry['day_off'])) {
$spec[] = array( '@type' => 'OpeningHoursSpecification', 'dayOfWeek' => $day, 'opens' => '00:00', 'closes' => '00:00' );
continue;
}
$from = isset($entry['opens']) ? trim((string) $entry['opens']) : '';
$to = isset($entry['closes']) ? trim((string) $entry['closes']) : '';
if ($from && $to) {
$spec[] = array( '@type' => 'OpeningHoursSpecification', 'dayOfWeek' => $day, 'opens' => $from, 'closes' => $to );
}
}
return $spec;
}
$hours_raw = get_option('branch_hours');
if (is_string($hours_raw) && '' !== trim($hours_raw)) {
foreach (explode("\n", $hours_raw) as $line) {
$line = trim($line);
if ('' === $line) {
continue;
}
$parts = explode('|', $line);
$day = isset($parts[0]) ? trim($parts[0]) : '';
if ('' === $day) {
continue;
}
if (isset($parts[2]) && 'closed' === strtolower(trim($parts[2]))) {
$spec[] = array( '@type' => 'OpeningHoursSpecification', 'dayOfWeek' => $day, 'opens' => '00:00', 'closes' => '00:00' );
continue;
}
$from = isset($parts[1]) ? trim($parts[1]) : '';
$to = isset($parts[2]) ? trim($parts[2]) : '';
if ($day && $from && $to) {
$spec[] = array( '@type' => 'OpeningHoursSpecification', 'dayOfWeek' => $day, 'opens' => $from, 'closes' => $to );
}
}
}
if (empty($spec)) {
foreach (array( 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday' ) as $day) {
$spec[] = array(
'@type' => 'OpeningHoursSpecification',
'dayOfWeek' => 'http://schema.org/' . $day,
'opens' => '08:30',
'closes' => '20:00',
);
}
}
return $spec;
}
function dekart_schema_hours_from_text($raw): array
{
$raw = is_string($raw) ? trim($raw) : '';
if ($raw === '') {
return array();
}
$raw = str_replace(array( '–', '—', '−' ), '-', $raw);
$raw = preg_replace('/\bдо\b/ui', '-', $raw);
$raw = mb_strtolower($raw);
$daymap = array(
'пн' => 'Monday', 'вт' => 'Tuesday', 'ср' => 'Wednesday', 'чт' => 'Thursday',
'пт' => 'Friday', 'сб' => 'Saturday', 'вс' => 'Sunday',
'понедельник' => 'Monday', 'вторник' => 'Tuesday', 'среда' => 'Wednesday',
'четверг' => 'Thursday', 'пятница' => 'Friday', 'суббота' => 'Saturday', 'воскресенье' => 'Sunday',
);
$order = array( 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday' );
$specs = array();
foreach (preg_split('/[,;]+/u', $raw) as $seg) {
$seg = trim($seg);
if ($seg === '' || ! preg_match('/(\d{1,2}:\d{2})\s*-\s*(\d{1,2}:\d{2})/u', $seg, $mt)) {
continue;
}
$opens = $mt[1];
$closes = $mt[2];
$days = array();
if (preg_match('/([а-яё]{2,3})\s*-\s*([а-яё]{2,3})/u', $seg, $mr) && isset($daymap[$mr[1]], $daymap[$mr[2]])) {
$ia = array_search($daymap[$mr[1]], $order);
$ib = array_search($daymap[$mr[2]], $order);
if ($ia !== false && $ib !== false) {
for ($i = min($ia, $ib); $i <= max($ia, $ib); $i++) {
$days[] = $order[$i];
}
}
}
if (! $days) {
if (false !== mb_strpos($seg, 'ежедневно')) {
$days = $order;
} else {
foreach ($daymap as $token => $full) {
if (false !== mb_strpos($seg, $token)) {
$days[] = $full;
}
}
}
}
if (preg_match('/кроме\s+([а-яё]+)/u', $seg, $mex)) {
$ex = $mex[1];
$exday = false !== mb_strpos($ex, 'воскрес') ? 'Sunday'
: ( false !== mb_strpos($ex, 'суббот') ? 'Saturday' : ( $daymap[$ex] ?? '' ) );
if ($exday) {
$days = array_values(array_diff($days, array( $exday )));
}
}
$days = array_values(array_unique($days));
if ($days) {
$specs[] = array(
'@type' => 'OpeningHoursSpecification',
'dayOfWeek' => $days,
'opens' => $opens,
'closes' => $closes,
);
}
}
return $specs;
}
function dekart_schema_local_business(): ?array
{
$page_url = dekart_schema_page_url();
$brand = (dekart_branch_option('branch_name') ?: dekart_site_name());
$street = get_option('branch_address') ?: carbon_get_theme_option('site_address') ?: '';
$city = (dekart_branch_option('branch_city') ?: dekart_branch_city());
$region = dekart_branch_option('branch_region');
$phone = dekart_branch_option('branch_phone', '');
$email = dekart_branch_option('branch_email') ?: carbon_get_theme_option('site_mail') ?: '';
$coords = get_option('branch_coords');
$lat = '';
$lng = '';
if (! empty($coords) && is_string($coords) && false !== strpos($coords, ',')) {
$parts = explode(',', $coords);
if (count($parts) >= 2) {
$lat = trim($parts[0]);
$lng = trim($parts[1]);
}
}
$zip = dekart_schema_option('schema_postal_code', 'branch_postal_code');
$price_range = get_option('branch_price_range');
$founded = dekart_schema_option('schema_founded', 'branch_founded');
$map_url = dekart_schema_option('schema_map_url', 'branch_map_url');
$google_place_id = get_option('branch_google_place_id');
$google_maps_url = get_option('branch_google_maps_url');
$area_served_raw = get_option('branch_area_served') ?: carbon_get_theme_option('schema_area_served') ?: dekart_branch_city();
$hours_cf = carbon_get_theme_option('schema_hours');
$lb = array(
'@type' => array( 'EducationalOrganization', 'LocalBusiness' ),
'@id' => $page_url . '#local-business',
'parentOrganization' => array(
'@id' => home_url('/') . '#organization',
),
'name' => wp_strip_all_tags($brand),
'address' => array(
'@type' => 'PostalAddress',
'streetAddress' => wp_strip_all_tags($street),
'addressLocality' => wp_strip_all_tags($city),
'addressRegion' => wp_strip_all_tags($region),
'addressCountry' => 'RU',
),
'url' => $page_url,
);
if ($phone) {
$lb['telephone'] = wp_strip_all_tags($phone);
}
if ($email) {
$lb['email'] = wp_strip_all_tags($email);
}
if (! empty($zip) && is_string($zip)) {
$lb['address']['postalCode'] = trim($zip);
}
if (! empty($lat) && ! empty($lng)) {
$lb['geo'] = array(
'@type' => 'GeoCoordinates',
'latitude' => floatval($lat),
'longitude' => floatval($lng),
);
}
if (! empty($google_maps_url) && is_string($google_maps_url)) {
$lb['hasMap'] = esc_url(trim($google_maps_url));
} elseif (! empty($map_url) && is_string($map_url)) {
$lb['hasMap'] = esc_url(trim($map_url));
}
$hours_spec = array();
if (! empty($hours_cf) && is_array($hours_cf)) {
foreach ($hours_cf as $entry) {
$day = isset($entry['day_of_week']) ? trim($entry['day_of_week']) : '';
if (empty($day)) {
continue;
}
$is_off = ! empty($entry['day_off']);
if ($is_off) {
$hours_spec[] = array(
'@type' => 'OpeningHoursSpecification',
'dayOfWeek' => $day,
'opens' => '00:00',
'closes' => '00:00',
);
} else {
$from = isset($entry['opens']) ? trim($entry['opens']) : '';
$to = isset($entry['closes']) ? trim($entry['closes']) : '';
if ($from && $to) {
$hours_spec[] = array(
'@type' => 'OpeningHoursSpecification',
'dayOfWeek' => $day,
'opens' => $from,
'closes' => $to,
);
}
}
}
} else {
$hours_raw = get_option('branch_hours');
if (! empty($hours_raw) && is_string($hours_raw)) {
$lines = explode("\n", $hours_raw);
foreach ($lines as $line) {
$line = trim($line);
if (empty($line)) {
continue;
}
$parts = explode('|', $line);
$day = isset($parts[0]) ? trim($parts[0]) : '';
if (empty($day)) {
continue;
}
if (isset($parts[2]) && 'closed' === strtolower(trim($parts[2]))) {
$hours_spec[] = array(
'@type' => 'OpeningHoursSpecification',
'dayOfWeek' => $day,
'opens' => '00:00',
'closes' => '00:00',
);
continue;
}
$from = isset($parts[1]) ? trim($parts[1]) : '';
$to = isset($parts[2]) ? trim($parts[2]) : '';
if ($day && $from && $to) {
$hours_spec[] = array(
'@type' => 'OpeningHoursSpecification',
'dayOfWeek' => $day,
'opens' => $from,
'closes' => $to,
);
}
}
}
}
if (empty($hours_spec)) {
$hours_text = get_option('branch_hours') ?: get_option('branch_work_hours');
$hours_spec = dekart_schema_hours_from_text($hours_text);
}
if (! empty($hours_spec)) {
$lb['openingHoursSpecification'] = $hours_spec;
}
if (! empty($price_range) && is_string($price_range)) {
$lb['priceRange'] = trim($price_range);
}
if (! empty($google_place_id) && is_string($google_place_id)) {
$lb['identifier'] = array(
'@type' => 'PropertyValue',
'name' => 'Google Place ID',
'value' => wp_strip_all_tags($google_place_id),
);
$lb['@id'] = 'https://search.google.com/local/writereview?placeid=' . urlencode($google_place_id);
}
$area_cities = array_filter(array_map('trim', preg_split('/[,;]+/u', (string) $area_served_raw)));
if ($city && ! in_array($city, $area_cities, true)) {
$area_cities[] = $city;
}
$lb['areaServed'] = array_values(array_map(function ($c) {
return array( '@type' => 'City', 'name' => wp_strip_all_tags($c) );
}, $area_cities));
if (! empty($founded) && is_string($founded)) {
$lb['foundingDate'] = trim($founded);
}
$social_cf = carbon_get_theme_option('schema_social');
$same_as = array();
if (! empty($social_cf) && is_array($social_cf)) {
foreach ($social_cf as $entry) {
$url = isset($entry['url']) ? trim($entry['url']) : '';
if ($url && filter_var($url, FILTER_VALIDATE_URL)) {
$same_as[] = esc_url($url);
}
}
} else {
$social_raw = get_option('branch_social');
if (! empty($social_raw) && is_array($social_raw)) {
foreach ($social_raw as $entry) {
$url = isset($entry['url']) ? trim($entry['url']) : '';
if ($url && filter_var($url, FILTER_VALIDATE_URL)) {
$same_as[] = esc_url($url);
}
}
}
}
if (! empty($same_as)) {
$lb['sameAs'] = $same_as;
}
$ensure_platforms = array(
'WhatsApp' => dekart_branch_option('branch_whatsapp', 'https://wa.me/79269311434'),
'Telegram' => dekart_branch_option('branch_telegram', 'https://t.me/dekart_school'),
);
foreach ($ensure_platforms as $platform => $url) {
if (! empty($url) && filter_var($url, FILTER_VALIDATE_URL)) {
$found = false;
foreach ($same_as as $existing) {
if (false !== stripos($existing, parse_url($url, PHP_URL_HOST))) {
$found = true;
break;
}
}
if (! $found) {
$same_as[] = esc_url($url);
}
}
}
$gbp_url = get_option('branch_google_business_url', '');
if (! empty($gbp_url) && filter_var($gbp_url, FILTER_VALIDATE_URL)) {
$found_gbp = false;
foreach ($same_as as $existing) {
if (false !== stripos($existing, parse_url($gbp_url, PHP_URL_HOST))) {
$found_gbp = true;
break;
}
}
if (! $found_gbp) {
$same_as[] = esc_url($gbp_url);
}
}
$yb_url = get_option('branch_yandex_business_url', '');
if (! empty($yb_url) && filter_var($yb_url, FILTER_VALIDATE_URL)) {
$found_yb = false;
foreach ($same_as as $existing) {
if (false !== stripos($existing, parse_url($yb_url, PHP_URL_HOST))) {
$found_yb = true;
break;
}
}
if (! $found_yb) {
$same_as[] = esc_url($yb_url);
}
}
$gis_url = get_option('branch_ext_2gis', '');
if (! empty($gis_url) && filter_var($gis_url, FILTER_VALIDATE_URL)) {
$found_gis = false;
foreach ($same_as as $existing) {
if (false !== stripos($existing, parse_url($gis_url, PHP_URL_HOST))) {
$found_gis = true;
break;
}
}
if (! $found_gis) {
$same_as[] = esc_url($gis_url);
}
}
if (! empty($same_as)) {
$lb['sameAs'] = $same_as;
}
$photos_cf = carbon_get_theme_option('schema_photos');
$images = array();
if (! empty($photos_cf) && is_array($photos_cf)) {
foreach ($photos_cf as $id) {
if (! is_numeric($id) || $id <= 0) {
continue;
}
$url = wp_get_attachment_url((int) $id);
if ($url) {
$images[] = esc_url($url);
}
}
} else {
$photos_raw = get_option('branch_photos');
if (! empty($photos_raw) && is_string($photos_raw)) {
$ids = explode(',', $photos_raw);
foreach ($ids as $id) {
$id = trim($id);
if (! is_numeric($id) || $id <= 0) {
continue;
}
$url = wp_get_attachment_url((int) $id);
if ($url) {
$images[] = esc_url($url);
}
}
}
}
if (! empty($images)) {
$lb['image'] = $images;
}
$teachers = carbon_get_post_meta(get_the_ID(), 'pksh_teachers');
if (! empty($teachers) && is_array($teachers)) {
$employee_ids = array();
foreach ($teachers as $i => $t) {
$t_id = isset($t['teacher_id']) ? intval($t['teacher_id']) : 0;
if ($t_id > 0) {
$employee_ids[] = array(
'@id' => $page_url . '#teacher-' . $i,
);
}
}
if (! empty($employee_ids)) {
$lb['employee'] = $employee_ids;
}
}
return $lb;
}
function dekart_schema_course(): ?array
{
$page_url = dekart_schema_page_url();
$name = carbon_get_post_meta(get_the_ID(), 'banner_h1') ?: 'Подготовка к школе 5–7 лет' . (dekart_branch_city() !== '' ? ' в ' . dekart_branch_city() : '');
$__fill = function ($s) {
return function_exists('dekart_fill_placeholders') ? dekart_fill_placeholders((string) $s) : (string) $s;
};
$course_name = trim((string) carbon_get_post_meta(get_the_ID(), 'pksh_course_name'));
if ('' !== $course_name) {
$name = $course_name;
}
// описание = видимый лид страницы
$visible_lead = $__fill(carbon_get_post_meta(get_the_ID(), 'pksh_hero_definition'));
$pksh_description = $__fill(carbon_get_post_meta(get_the_ID(), 'pksh_description'));
$description = '' !== trim((string) $visible_lead) ? $visible_lead : ( ! empty($pksh_description) ? $pksh_description : $__fill( carbon_get_post_meta(get_the_ID(), 'banner_subtitle') ?: 'Научим читать, считать и писать до школы. Бесплатное пробное занятие.' ) );
$has_trial = ! empty($pksh_description) && false !== mb_stripos($description, 'бесплатно');
$level = $__fill(carbon_get_post_meta(get_the_ID(), 'pksh_level'));
$age = $__fill(carbon_get_post_meta(get_the_ID(), 'pksh_age'));
$audience = $__fill(carbon_get_post_meta(get_the_ID(), 'pksh_audience'));
$course_mode = carbon_get_post_meta(get_the_ID(), 'pksh_course_mode');
$skills = carbon_get_post_meta(get_the_ID(), 'pksh_skills');
$course_img = carbon_get_post_meta(get_the_ID(), 'banner_img');
$programs = carbon_get_post_meta(get_the_ID(), 'pksh_programs');
$course = array(
'@type' => 'Course',
'@id' => $page_url . '#course',
'name' => wp_strip_all_tags($name),
'description' => wp_strip_all_tags($description),
'url' => $page_url,
'inLanguage' => 'ru-RU',
'provider' => array(
'@id' => home_url('/') . '#organization',
),
);
if ($has_trial) {
$course['hasCourseInstance'] = array(
'@type' => 'CourseInstance',
'courseMode' => 'Onsite',
'courseWorkload' => '30-40 минут',
);
}
if (! empty($level) && is_string($level)) {
$course['educationalLevel'] = wp_strip_all_tags(trim($level));
}
if (! empty($age) && is_string($age)) {
$course['typicalAgeRange'] = wp_strip_all_tags(trim($age));
}
if (! empty($audience) && is_string($audience)) {
$course['audience'] = array(
'@type' => 'EducationalAudience',
'name' => wp_strip_all_tags(trim($audience)),
);
}
if (! empty($skills) && is_array($skills)) {
$teaches = array();
foreach ($skills as $skill) {
$s = isset($skill['skill']) ? trim($skill['skill']) : '';
if ($s) {
$teaches[] = wp_strip_all_tags($s);
}
}
if (! empty($teaches)) {
$course['teaches'] = $teaches;
}
}
if (! empty($course_img)) {
if (is_array($course_img) && isset($course_img['url'])) {
$course['image'] = esc_url($course_img['url']);
} else {
$url = wp_get_attachment_url($course_img);
if ($url) {
$course['image'] = esc_url($url);
}
}
} elseif (has_post_thumbnail(get_the_ID())) {
$course['image'] = esc_url(get_the_post_thumbnail_url(get_the_ID(), 'full'));
}
// ровно два абонемента из CF
$course_offers = array();
foreach (array( 'base' => 'pksh_prog_base_price_sub', 'prem' => 'pksh_prog_prem_price_sub' ) as $slug => $meta_key) {
$price = dekart_parse_price((string) carbon_get_post_meta(get_the_ID(), $meta_key));
if ($price <= 0) {
continue;
}
$course_offers[] = array(
'@type' => 'Offer',
'@id' => $page_url . '#offer-' . $slug,
'price' => (string) (int) $price,
'priceCurrency' => 'RUB',
'availability' => 'https://schema.org/InStock',
'validFrom' => gmdate('Y-m-d'),
'url' => $page_url,
'offeredBy' => array(
'@id' => home_url('/') . '#organization',
),
'priceSpecification' => array(
'@type' => 'UnitPriceSpecification',
'price' => (string) (int) $price,
'priceCurrency' => 'RUB',
'unitCode' => 'MON',
'unitText' => 'месяц',
),
);
}
if (count($course_offers) === 2) {
$course['offers'] = $course_offers;
}
return $course;
}
function dekart_schema_rating(): ?array
{
$page_url = dekart_schema_page_url();
$ratings = array();
$reviews = carbon_get_post_meta(get_the_ID(), 'pksh_reviews_list');
if (is_array($reviews)) {
foreach ($reviews as $review) {
$rating = isset($review['review_rating']) ? (float) str_replace(',', '.', (string) $review['review_rating']) : 0;
if ($rating >= 1 && $rating <= 5) {
$ratings[] = $rating;
}
}
}
if (count($ratings) > 0) {
$average = round(array_sum($ratings) / count($ratings), 1);
$count = count($ratings);
} else {
$branch_avg = str_replace(',', '.', (string) get_option('branch_avg_rating', ''));
$count = (int) get_option('branch_reviews_count', 0);
if ('' === $branch_avg || ! is_numeric($branch_avg) || $count < 1) {
return null;
}
$average = round((float) $branch_avg, 1);
}
return array(
'@type' => 'AggregateRating',
'@id' => $page_url . '#aggregate-rating',
'ratingValue' => number_format($average, 1, '.', ''),
'bestRating' => '5',
'worstRating' => '1',
'ratingCount' => (string) $count,
);
}
function dekart_schema_service(): ?array
{
$page_url = dekart_schema_page_url();
$name = carbon_get_post_meta(get_the_ID(), 'banner_h1') ?: 'Подготовка к школе 5–7 лет' . (dekart_branch_city() !== '' ? ' в ' . dekart_branch_city() : '');
return array(
'@type' => 'Service',
'@id' => $page_url . '#service',
'name' => wp_strip_all_tags($name),
'provider' => array(
'@id' => $page_url . '#local-business',
),
'areaServed' => array(
'@type' => 'City',
'name' => (dekart_branch_option('branch_city') ?: dekart_branch_city()),
),
);
}
function dekart_schema_faq(): ?array
{
$page_url = dekart_schema_page_url();
$faq_items = carbon_get_post_meta(get_the_ID(), 'pksh_faq_items');
if (empty($faq_items) || ! is_array($faq_items)) {
return null;
}
$main_entity = array();
foreach ($faq_items as $item) {
$q = isset($item['faq_question']) ? trim($item['faq_question']) : '';
$a = isset($item['faq_answer']) ? trim($item['faq_answer']) : '';
if (empty($q) || empty($a)) {
continue;
}
$main_entity[] = array(
'@type' => 'Question',
'name' => wp_strip_all_tags($q),
'acceptedAnswer' => array(
'@type' => 'Answer',
'text' => wp_strip_all_tags($a),
),
);
}
if (empty($main_entity)) {
return null;
}
return array(
'@type' => 'FAQPage',
'@id' => $page_url . '#faq',
'name' => 'Часто задаваемые вопросы о подготовке к школе',
'mainEntity' => $main_entity,
);
}
function dekart_schema_teachers(): array
{
$page_url = dekart_schema_page_url();
$teachers = carbon_get_post_meta(get_the_ID(), 'pksh_teachers');
if (empty($teachers) || ! is_array($teachers)) {
return array();
}
$result = array();
foreach ($teachers as $i => $teacher) {
$t_id = isset($teacher['teacher_id']) ? intval($teacher['teacher_id']) : 0;
$subject = isset($teacher['teacher_subject']) ? trim($teacher['teacher_subject']) : '';
$about = isset($teacher['teacher_about']) ? trim($teacher['teacher_about']) : '';
if ($t_id < 1) {
continue;
}
$t_post = get_post($t_id);
if (! $t_post) {
continue;
}
$name = $t_post->post_title;
if (empty($name)) {
continue;
}
$photo = get_post_meta($t_id, '_teacher_avatar', true);
if (! $photo) {
$photo = get_post_meta($t_id, '_thumbnail_id', true);
}
if (empty($subject)) {
$subject = get_post_meta($t_id, '_teacher_direction', true);
}
if (empty($about)) {
$about = get_post_meta($t_id, '_teacher_about', true);
}
$person = array(
'@type' => 'Person',
'@id' => $page_url . '#teacher-' . $i,
'name' => wp_strip_all_tags($name),
);
if (! empty($subject) && is_string($subject)) {
$person['jobTitle'] = wp_strip_all_tags(trim($subject));
}
if (! empty($about) && is_string($about)) {
$person['description'] = wp_strip_all_tags(trim($about));
}
if (! empty($photo)) {
$url = wp_get_attachment_url((int) $photo);
if ($url) {
$person['image'] = esc_url($url);
}
}
$result[] = $person;
}
return $result;
}
function dekart_schema_reviews(): array
{
$page_url = dekart_schema_page_url();
$reviews = carbon_get_post_meta(get_the_ID(), 'pksh_reviews_list');
if (empty($reviews) || ! is_array($reviews)) {
return array();
}
if (function_exists('dekart_reviews_sort_desc')) {
$reviews = dekart_reviews_sort_desc($reviews);
}
$result = array();
$review_seq = 0;
foreach ($reviews as $i => $review) {
$author_name = isset($review['review_author']) ? trim($review['review_author']) : '';
$body = isset($review['review_text']) ? trim($review['review_text']) : '';
$rating_val = isset($review['review_rating']) ? intval($review['review_rating']) : 0;
if (empty($author_name) || empty($body)) {
continue;
}
if ($rating_val < 1 || $rating_val > 5) {
continue;
}
$review_seq++;
$entity = array(
'@type' => 'Review',
'@id' => $page_url . '#review-' . $review_seq,
'author' => array(
'@type' => 'Person',
'name' => wp_strip_all_tags($author_name),
),
'reviewBody' => wp_strip_all_tags($body),
'reviewRating' => array(
'@type' => 'Rating',
'ratingValue' => (string) $rating_val,
'bestRating' => '5',
'worstRating' => '1',
),
);
$review_date = isset($review['review_date']) ? trim($review['review_date']) : '';
if ($review_date) {
$entity['datePublished'] = sanitize_text_field($review_date);
}
$result[] = $entity;
}
return $result;
}
function dekart_author_canon(array $args = array()): array
{
$args = wp_parse_args($args, array(
'author_name' => '',
'author_creds' => '',
'author_years' => null,
'stazh_format' => '%1$d %2$s',
));
$name = (string) $args['author_name'];
$creds = (string) $args['author_creds'];
if (class_exists('Pksh_Data')) {
$data = Pksh_Data::instance();
if ('' === $name) {
$name = $data->get_author_name();
}
if ('' === $creds) {
$creds = $data->get_author_creds();
}
}
$years = $args['author_years'];
$stazh = (null !== $years && (int) $years > 0)
? sprintf($args['stazh_format'], (int) $years, function_exists('dekart_years_plural') ? dekart_years_plural((int) $years) : 'лет')
: '';
return array(
'name' => $name,
'creds' => $creds,
'years' => $years,
'stazh' => $stazh,
);
}
function dekart_schema_author(): ?array
{
$page_url = dekart_schema_page_url();
$canon = dekart_author_canon();
$title = $canon['creds'];
if ($canon['stazh'] !== '') {
$title = $title !== '' ? $title . ', ' . $canon['stazh'] : $canon['stazh'];
}
$person = array(
'@type' => 'Person',
'@id' => $page_url . '#author',
'name' => wp_strip_all_tags($canon['name']),
);
if ($title !== '') {
$person['jobTitle'] = wp_strip_all_tags($title);
}
$person['description'] = wp_strip_all_tags(trim(sprintf(
'Автор контента %s%s',
$canon['name'],
$title !== '' ? ' — ' . $title : ''
)));
return $person;
}
function dekart_schema_trial_event(): ?array
{
if (! is_page_template('page-podgotovka-k-shkole.php')) {
return null;
}
$page_url = dekart_schema_page_url();
$subtitle = carbon_get_post_meta(get_the_ID(), 'banner_subtitle');
$has_trial = ! empty($subtitle) && false !== mb_stripos($subtitle, 'бесплатно');
if (! $has_trial) {
return null;
}
$tz = wp_timezone();
$now = new DateTimeImmutable('now', $tz);
$start = null;
$cf_start = (string) carbon_get_post_meta(get_the_ID(), 'pksh_trial_event_start_date');
if ('' !== $cf_start) {
try {
$candidate = new DateTimeImmutable($cf_start, $tz);
if ($candidate > $now) {
$start = $candidate;
}
} catch (Exception $e) {
$start = null;
}
}
if (null === $start) {
$weekday = (int) get_option('branch_trial_weekday', 6);
$time = (string) (get_option('branch_trial_time', '10:00') ?: '10:00');
$parts = array_map('intval', explode(':', $time));
$start = $now->setTime($parts[0] ?? 10, $parts[1] ?? 0);
$diff = ( $weekday - (int) $now->format('N') + 7 ) % 7;
if ($diff > 0 || $start <= $now) {
$start = $start->modify('+' . ($diff > 0 ? $diff : 7) . ' days');
}
}
$end = $start->modify('+1 hour');
$cf_end = (string) carbon_get_post_meta(get_the_ID(), 'pksh_trial_event_end_date');
if ('' !== $cf_end) {
try {
$candidate_end = new DateTimeImmutable($cf_end, $tz);
if ($candidate_end > $start) {
$end = $candidate_end;
}
} catch (Exception $e) {
}
}
$start_date = $start->format('c');
$end_date = $end->format('c');
$location = array(
'@type' => 'Place',
'name' => dekart_site_name(),
'address' => array(
'@type' => 'PostalAddress',
'streetAddress' => get_option('branch_address') ?: carbon_get_theme_option('site_address'),
'addressLocality' => (get_option('branch_city') ?: dekart_branch_city()),
'addressRegion' => get_option('branch_region', 'Московская область'),
'addressCountry' => 'RU',
),
);
$post_id = get_the_ID();
return array(
'@type' => 'Event',
'@id' => $page_url . '#trial-event',
'name' => 'Бесплатное пробное занятие: Подготовка к школе',
'description' => 'Полноценное занятие + диагностика готовности к школе. Ребёнок познакомится с педагогом, выполнит тестовые задания. Родители получат план подготовки.',
'eventStatus' => 'https://schema.org/EventScheduled',
'eventAttendanceMode' => 'https://schema.org/OfflineEventAttendanceMode',
'startDate' => $start_date,
'endDate' => $end_date,
'location' => $location,
'offers' => array(
'@type' => 'Offer',
'@id' => $page_url . '#offer-trial',
'price' => '0',
'priceCurrency' => 'RUB',
'availability' => 'https://schema.org/LimitedAvailability',
'description' => 'Бесплатное пробное занятие',
'category' => 'Бесплатное пробное занятие',
),
'organizer' => array(
'@id' => home_url('/') . '#organization',
),
'image' => ( $post_id && has_post_thumbnail($post_id) )
? get_the_post_thumbnail_url($post_id, 'full')
: '',
);
}
function dekart_schema_offer(): ?array
{
$page_url = dekart_schema_page_url();
$base_price = carbon_get_post_meta(get_the_ID(), 'pksh_prog_base_price_sub');
$prem_price = carbon_get_post_meta(get_the_ID(), 'pksh_prog_prem_price_sub');
$price_valid = carbon_get_post_meta(get_the_ID(), 'pksh_price_valid_until');
$offers = array();
$prices = array();
foreach (array( $base_price, $prem_price ) as $raw) {
if (! empty($raw) && is_string($raw)) {
$parsed = dekart_parse_price($raw);
if ($parsed > 0) {
$prices[] = $parsed;
}
}
}
if (empty($prices)) {
$offer = array(
'@type' => 'Offer',
'@id' => $page_url . '#offer',
'price' => '0',
'priceCurrency' => 'RUB',
'description' => 'Подготовка к школе — свяжитесь для уточнения стоимости',
'availability' => 'https://schema.org/InStock',
'category' => 'Образовательные услуги',
);
if (! empty($price_valid)) {
$offer['priceValidUntil'] = trim($price_valid);
}
$offers[] = $offer;
return $offers;
}
$labels = array( 'Базовая программа', 'Расширенная программа' );
$i = 0;
foreach (array( $base_price, $prem_price ) as $raw) {
$price = dekart_parse_price((string) $raw);
if ($price <= 0) {
continue;
}
$offer = array(
'@type' => 'Offer',
'@id' => $page_url . '#offer-' . ( 0 === $i ? 'base' : 'prem' ),
'name' => $labels[$i] ?? '',
'price' => (string) (int) $price,
'priceCurrency' => 'RUB',
'availability' => 'https://schema.org/InStock',
'validFrom' => gmdate('Y-m-d'),
'category' => 'Образовательные услуги',
'offeredBy' => array(
'@id' => $page_url . '#organization',
),
'priceSpecification' => array(
'@type' => 'UnitPriceSpecification',
'price' => (string) (int) $price,
'priceCurrency' => 'RUB',
'unitCode' => 'MON',
'unitText' => 'месяц',
),
);
if (! empty($price_valid)) {
$offer['priceValidUntil'] = trim($price_valid);
}
$offers[] = $offer;
$i++;
}
$subtitle = carbon_get_post_meta(get_the_ID(), 'banner_subtitle');
if (! empty($subtitle) && false !== mb_stripos($subtitle, 'бесплатно')) {
$trial = array(
'@type' => 'Offer',
'@id' => $page_url . '#offer-trial',
'price' => '0',
'priceCurrency' => 'RUB',
'availability' => 'https://schema.org/LimitedAvailability',
'description' => wp_strip_all_tags($subtitle),
'category' => 'Бесплатное пробное занятие',
'offeredBy' => array(
'@id' => $page_url . '#local-business',
),
);
if (! empty($price_valid)) {
$trial['priceValidUntil'] = trim($price_valid);
}
$offers[] = $trial;
}
return $offers;
}
function dekart_parse_price(string $raw): float
{
$clean = preg_replace('/[^0-9.,]/', '', $raw);
if (empty($clean)) {
return 0.0;
}
$last_dot = strrpos($clean, '.');
$last_comma = strrpos($clean, ',');
if (false !== $last_comma && ( false === $last_dot || $last_comma > $last_dot )) {
$clean = str_replace('.', '', $clean);
$clean = str_replace(',', '.', $clean);
} else {
$clean = str_replace(',', '', $clean);
$clean = preg_replace('/\.(?=.*\.)/', '', $clean);
}
return (float) $clean;
}
// Blog JSON-LD: BlogPosting / BreadcrumbList / ItemList
add_action('wp_head', 'dekart_blog_jsonld', 3);
function dekart_blog_jsonld(): void
{
if (is_admin() || is_feed() || is_robots()) {
return;
}
$is_post = is_singular('post');
$is_blog = is_home();
if (! $is_post && ! $is_blog) {
return;
}
$home = untrailingslashit(home_url('/'));
$blog = get_page_by_path('novosti');
$blog_url = $blog ? (string) get_permalink($blog) : $home . '/novosti/';
$blocks = array();
if ($is_post) {
$post_id = (int) get_the_ID();
$canon = dekart_author_canon(); // phpcs:ignore
$pub_name = (string) get_option('branch_og_site_name');
if ('' === trim($pub_name)) {
$pub_name = (string) get_option('branch_name');
}
if ('' === trim($pub_name)) {
$pub_name = (string) get_bloginfo('name');
}
$pa = function_exists('dekart_post_author') ? dekart_post_author($post_id) : array( 'name' => '', 'url' => '' );
$author_person = array( '@type' => 'Person', 'name' => wp_strip_all_tags((string) $pa['name']) );
if ('' !== (string) $pa['url']) {
$author_person['url'] = (string) $pa['url'];
}
$posting = array(
'@context' => 'https://schema.org',
'@type' => 'BlogPosting',
'mainEntityOfPage' => array( '@type' => 'WebPage', '@id' => get_permalink($post_id) ),
'headline' => wp_strip_all_tags(get_the_title($post_id)),
'datePublished' => get_the_date('c', $post_id),
'dateModified' => get_the_modified_date('c', $post_id),
'author' => $author_person,
'publisher' => array( '@type' => 'Organization', 'name' => wp_strip_all_tags($pub_name), 'url' => $home . '/' ),
);
$desc = wp_strip_all_tags(get_the_excerpt($post_id));
if ('' !== trim($desc)) {
$posting['description'] = $desc;
}
if (has_post_thumbnail($post_id)) {
$posting['image'] = (string) get_the_post_thumbnail_url($post_id, 'full');
}
$blocks[] = $posting;
$faq_rows = function_exists('dekart_post_faq_rows') ? dekart_post_faq_rows($post_id) : array();
$questions = array();
foreach ($faq_rows as $row) {
$q = trim((string) ( $row['q'] ?? '' ));
$a = trim((string) ( $row['a'] ?? '' ));
if ('' === $q || '' === $a) {
continue;
}
$questions[] = array(
'@type' => 'Question',
'name' => $q,
'acceptedAnswer' => array( '@type' => 'Answer', 'text' => $a ),
);
}
if (! empty($questions)) {
$blocks[] = array( '@context' => 'https://schema.org', '@type' => 'FAQPage', 'mainEntity' => $questions );
}
}
$crumbs = array(
array( '@type' => 'ListItem', 'position' => 1, 'name' => 'Главная', 'item' => $home . '/' ),
array( '@type' => 'ListItem', 'position' => 2, 'name' => function_exists('dekart_blog_label') ? dekart_blog_label() : 'Статьи', 'item' => $blog_url ),
);
if ($is_post) {
$crumbs[] = array( '@type' => 'ListItem', 'position' => 3, 'name' => wp_strip_all_tags(get_the_title()), 'item' => get_permalink() );
}
$blocks[] = array( '@context' => 'https://schema.org', '@type' => 'BreadcrumbList', 'itemListElement' => $crumbs );
if ($is_blog) {
$posts = get_posts(array( 'post_type' => 'post', 'posts_per_page' => 20, 'post_status' => 'publish' ));
$items = array();
foreach ($posts as $i => $p) {
$items[] = array(
'@type' => 'ListItem',
'position' => $i + 1,
'url' => get_permalink($p),
'name' => wp_strip_all_tags(get_the_title($p)),
);
}
if (! empty($items)) {
$blocks[] = array(
'@context' => 'https://schema.org',
'@type' => 'Blog',
'name' => function_exists('dekart_blog_label') ? dekart_blog_label() : 'Статьи',
'url' => $blog_url,
'mainEntity' => array( '@type' => 'ItemList', 'itemListElement' => $items ),
);
}
}
foreach ($blocks as $block) {
echo '<script type="application/ld+json">' . wp_json_encode($block, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES) . '</script>' . "\n";
}
}
// Лендинги: Service/ChildCare + FAQPage + BreadcrumbList
add_action('wp_head', 'dekart_landing_jsonld', 2);
function dekart_landing_jsonld(): void
{
if (is_admin() || is_feed() || is_robots()) {
return;
}
if (! function_exists('dekart_is_landing_template') || ! dekart_is_landing_template()) {
return;
}
// pksh уже отдаётся dekart_schema_output
if (is_page_template('page-podgotovka-k-shkole.php')) {
return;
}
$schema_templates = (array) apply_filters('dekart_landing_schema_templates', array( 'page-after-school.php' ));
$current_id = (int) get_queried_object_id();
$current_template = (string) get_page_template_slug($current_id);
if ('' === $current_template && $current_id) {
$current_template = (string) get_post_meta($current_id, '_wp_page_template', true);
}
// запасные триггеры: FAQ в CF или любой лендинг-шаблон
$has_landing_faq = $current_id && ! empty(carbon_get_post_meta($current_id, 'as_questions'));
$is_landing = function_exists('dekart_is_landing_template') && dekart_is_landing_template();
if (! in_array($current_template, $schema_templates, true) && ! $has_landing_faq && ! $is_landing) {
return;
}
if (! function_exists('carbon_get_post_meta')) {
return;
}
$post_id = (int) get_the_ID();
if ($post_id < 1) {
return;
}
$url = (string) get_permalink($post_id);
$graph = array();
$organization = dekart_schema_organization();
if ($organization) {
$graph[] = $organization;
}
$type = (string) carbon_get_post_meta($post_id, 'landing_schema_type');
if (! in_array($type, array( 'Service', 'ChildCare' ), true)) {
$type = 'Service';
}
$name = (string) carbon_get_post_meta($post_id, 'landing_service_name');
if ('' === trim($name)) {
$name = (string) carbon_get_post_meta($post_id, 'banner_h1');
}
if ('' === trim($name)) {
$name = (string) get_the_title($post_id);
}
$area_city = dekart_branch_option('branch_city', '');
$service = array(
'@type' => $type,
'@id' => $url . '#service',
'name' => wp_strip_all_tags($name),
'url' => $url,
'provider' => array( '@id' => home_url('/') . '#organization' ),
);
if ('' !== $area_city) {
$service['areaServed'] = array(
'@type' => 'City',
'name' => $area_city,
);
}
$graph[] = $service;
$main_entity = dekart_schema_faq_rows(
carbon_get_post_meta($post_id, 'as_questions'),
'questions_question',
'questions_answer'
);
if (! empty($main_entity)) {
$graph[] = array(
'@type' => 'FAQPage',
'@id' => $url . '#faq',
'mainEntity' => $main_entity,
);
}
// Крошки: CF-цепочка, иначе Главная → заголовок
$crumbs = array( array( 'name' => 'Главная', 'item' => home_url('/') ) );
$cf_trail = carbon_get_post_meta($post_id, 'as_breadcrumbs');
foreach ((array) $cf_trail as $row) {
$c_name = trim((string) ( $row['breadcrumbs_name'] ?? '' ));
if ('' === $c_name) {
continue;
}
$crumbs[] = array(
'name' => $c_name,
'item' => trim((string) ( $row['breadcrumbs_link'] ?? '' )),
);
}
$crumb_last = trim((string) carbon_get_post_meta($post_id, 'banner_h1'));
if ('' === $crumb_last) {
$crumb_last = (string) get_the_title($post_id);
}
$crumbs[] = array( 'name' => wp_strip_all_tags($crumb_last), 'item' => $url );
$list = array();
foreach ($crumbs as $i => $crumb) {
$node = array(
'@type' => 'ListItem',
'position' => $i + 1,
'name' => $crumb['name'],
);
if ('' !== $crumb['item']) {
$node['item'] = $crumb['item'];
}
$list[] = $node;
}
$graph[] = array(
'@type' => 'BreadcrumbList',
'@id' => $url . '#breadcrumb',
'itemListElement' => $list,
);
echo '<script type="application/ld+json">' . wp_json_encode(
array( '@context' => 'https://schema.org', '@graph' => $graph ),
JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES
) . '</script>' . "\n";
}
function dekart_schema_faq_rows($rows, string $q_key, string $a_key): array
{
if (empty($rows) || ! is_array($rows)) {
return array();
}
$main_entity = array();
foreach ($rows as $item) {
$q = isset($item[ $q_key ]) ? trim((string) $item[ $q_key ]) : '';
$a = isset($item[ $a_key ]) ? trim((string) $item[ $a_key ]) : '';
if ('' === $q || '' === $a) {
continue;
}
$main_entity[] = array(
'@type' => 'Question',
'name' => wp_strip_all_tags($q),
'acceptedAnswer' => array(
'@type' => 'Answer',
'text' => wp_strip_all_tags($a),
),
);
}
return $main_entity;
}