101 lines
3.0 KiB
PHP
101 lines
3.0 KiB
PHP
<?php
|
|
declare(strict_types=1);
|
|
|
|
namespace WPMultiCity;
|
|
|
|
final class Router
|
|
{
|
|
public static function register(): void
|
|
{
|
|
\add_action('wp', [self::class, 'route'], 9999);
|
|
\add_filter('query_vars', [self::class, 'add_town_query_var']);
|
|
}
|
|
|
|
public static function add_town_query_var(array $vars): array
|
|
{
|
|
$vars[] = 'town';
|
|
return $vars;
|
|
}
|
|
|
|
public static function route(): void
|
|
{
|
|
if (\is_admin()) {
|
|
return;
|
|
}
|
|
if (\defined('DOING_AJAX') && \DOING_AJAX) {
|
|
return;
|
|
}
|
|
$town_slug = Helpers::current_town();
|
|
if ($town_slug === null) {
|
|
return;
|
|
}
|
|
$main = Helpers::main_town_slug();
|
|
if ($main !== null && $town_slug === $main) {
|
|
return;
|
|
}
|
|
$request_uri = $_SERVER['REQUEST_URI'] ?? '/';
|
|
if (!Helpers::is_routable_path($request_uri)) {
|
|
return;
|
|
}
|
|
|
|
$url_original = self::strip_town_prefix($request_uri, $town_slug);
|
|
|
|
if (self::is_root($url_original)) {
|
|
$term = Helpers::get_term_by_slug($town_slug);
|
|
if ($term === null) {
|
|
return;
|
|
}
|
|
$page_id = 0;
|
|
if (\function_exists('get_field')) {
|
|
$page_id = (int) (\get_field('main_page_alt', 'town_' . $term->term_id) ?? 0);
|
|
}
|
|
if (!$page_id) {
|
|
$fallback = Helpers::index_town_alt_page_id();
|
|
if ($fallback === null) {
|
|
return;
|
|
}
|
|
$page_id = $fallback;
|
|
}
|
|
self::install_query($page_id, $town_slug, true);
|
|
return;
|
|
}
|
|
|
|
$page_id = \url_to_postid($url_original);
|
|
if (!$page_id) {
|
|
return;
|
|
}
|
|
$swap = Helpers::page_unic_swap($page_id, $town_slug);
|
|
if ($swap !== null) {
|
|
$page_id = $swap;
|
|
}
|
|
self::install_query($page_id, $town_slug, false);
|
|
}
|
|
|
|
private static function strip_town_prefix(string $uri, string $town_slug): string
|
|
{
|
|
$path = strtok($uri, '?');
|
|
$query = (strpos($uri, '?') !== false) ? substr($uri, strpos($uri, '?')) : '';
|
|
$new_path = preg_replace('#^/' . preg_quote($town_slug, '#') . '(/|$)#', '/', (string) $path);
|
|
return ($new_path ?? '/') . $query;
|
|
}
|
|
|
|
private static function is_root(string $url): bool
|
|
{
|
|
$path = strtok($url, '?');
|
|
return $path === '/' || $path === false || $path === '';
|
|
}
|
|
|
|
private static function install_query(int $page_id, string $town_slug, bool $is_front_page): void
|
|
{
|
|
global $wp_query, $wp_the_query, $post;
|
|
$post = \get_post($page_id);
|
|
$wp_query = new \WP_Query(['page_id' => $page_id, 'town' => $town_slug]);
|
|
$wp_query->is_page = true;
|
|
if ($is_front_page) {
|
|
$wp_query->is_front_page = true;
|
|
}
|
|
$wp_the_query = $wp_query;
|
|
\status_header(200);
|
|
}
|
|
}
|