Files
wp-multi-city/includes/class-redirect.php
T
Vladimir Bryzgalov 07ed1703ba
tests / phpunit (push) Has been cancelled
fix(wpmc 1.1.0): review polish — continue on bad permalink, ACF guard, drop suppress_filters, process-isolated AJAX test
- Redirect::handle: continue instead of return when get_permalink fails on a row (allow trying next row)
- Helpers::acf_ready() now public so Redirect can guard get_field('page_unic', ...) consistently
- Drop suppress_filters=false from get_posts (was risky on sites with query-altering plugins)
- @runInSeparateProcess for DOING_AJAX test (replaces Z-prefix ordering hack)

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-19 02:30:26 +05:00

96 lines
2.7 KiB
PHP

<?php
declare(strict_types=1);
namespace WPMultiCity;
final class Redirect
{
public static function register(): void
{
\add_action('template_redirect', [self::class, 'handle'], 1);
}
public static function handle(): void
{
if (\is_admin() || (\defined('DOING_AJAX') && \DOING_AJAX)) {
return;
}
if (!\is_404()) {
return;
}
$main = Helpers::main_town_slug();
if ($main === null) {
return;
}
$slug = self::extract_last_segment($_SERVER['REQUEST_URI'] ?? '/');
if ($slug === null) {
return;
}
$candidates = \get_posts([
'name' => $slug,
'post_type' => 'page',
'post_status' => ['private', 'publish'],
'posts_per_page' => 1,
'no_found_rows' => true,
]);
if (empty($candidates)) {
return;
}
$candidate_id = (int) $candidates[0]->ID;
if (!Helpers::acf_ready() || !\function_exists('get_field')) {
return;
}
$rows = \get_field('page_unic', 'option');
if (!is_array($rows)) {
return;
}
foreach ($rows as $row) {
if (!is_array($row)) {
continue;
}
if ((int) ($row['page_new'] ?? 0) !== $candidate_id) {
continue;
}
$town_term_id = (int) ($row['town'] ?? 0);
$orig_id = (int) ($row['page_old'] ?? 0);
if (!$town_term_id || !$orig_id) {
continue;
}
$term = \get_term_by('id', $town_term_id, 'town');
if (!($term instanceof \WP_Term) || $term->slug === '' || $term->slug === $main) {
continue;
}
$orig_permalink = Helpers::without_url_filters(
static fn () => \get_permalink($orig_id)
);
if (!is_string($orig_permalink) || $orig_permalink === '') {
continue;
}
$path_only = Helpers::remove_domain_link($orig_permalink);
$redirect_to = '/' . $term->slug . $path_only;
\wp_safe_redirect($redirect_to, 301);
exit;
}
}
private static function extract_last_segment(string $uri): ?string
{
$path = strtok($uri, '?');
if ($path === false) {
return null;
}
$parts = array_values(array_filter(
explode('/', $path),
static fn (string $p) => $p !== ''
));
$last = end($parts);
return $last !== false && $last !== '' ? $last : null;
}
}