f81cefefbe
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
76 lines
2.2 KiB
PHP
76 lines
2.2 KiB
PHP
<?php
|
|
declare(strict_types=1);
|
|
|
|
namespace WPMultiCity;
|
|
|
|
final class Helpers
|
|
{
|
|
private static ?string $current_town_memo = null;
|
|
private static bool $current_town_resolved = false;
|
|
private static array $term_cache = [];
|
|
|
|
public static function reset_cache(): void
|
|
{
|
|
self::$current_town_memo = null;
|
|
self::$current_town_resolved = false;
|
|
self::$term_cache = [];
|
|
}
|
|
|
|
public static function get_term_by_slug(string $slug, string $taxonomy = 'town'): ?\WP_Term
|
|
{
|
|
$key = $taxonomy . '|' . $slug;
|
|
if (array_key_exists($key, self::$term_cache)) {
|
|
return self::$term_cache[$key];
|
|
}
|
|
$term = \get_term_by('slug', $slug, $taxonomy);
|
|
return self::$term_cache[$key] = ($term instanceof \WP_Term) ? $term : null;
|
|
}
|
|
|
|
public static function current_town(): ?string
|
|
{
|
|
if (self::$current_town_resolved) {
|
|
return self::$current_town_memo;
|
|
}
|
|
|
|
$uri = $_SERVER['REQUEST_URI'] ?? '/';
|
|
$first_segment = self::first_path_segment($uri);
|
|
|
|
$resolved = null;
|
|
if ($first_segment !== null) {
|
|
$terms = \get_terms('town', [
|
|
'hide_empty' => false,
|
|
'fields' => 'id=>slug',
|
|
]);
|
|
if (is_array($terms) && in_array($first_segment, $terms, true)) {
|
|
$resolved = $first_segment;
|
|
}
|
|
}
|
|
|
|
if ($resolved === null) {
|
|
$resolved = \apply_filters('wpmc_main_town_slug', null);
|
|
if (!is_string($resolved) || $resolved === '') {
|
|
$resolved = null;
|
|
}
|
|
}
|
|
|
|
$resolved = \apply_filters('wpmc_current_town_slug', $resolved);
|
|
if (!is_string($resolved) || $resolved === '') {
|
|
$resolved = null;
|
|
}
|
|
|
|
self::$current_town_memo = $resolved;
|
|
self::$current_town_resolved = true;
|
|
return $resolved;
|
|
}
|
|
|
|
private static function first_path_segment(string $uri): ?string
|
|
{
|
|
$path = strtok($uri, '?');
|
|
if ($path === false) {
|
|
return null;
|
|
}
|
|
$parts = array_values(array_filter(explode('/', $path), static fn(string $p) => $p !== ''));
|
|
return $parts[0] ?? null;
|
|
}
|
|
}
|