43e3efc5a2
Replace old triggering-on-page_new semantics with washanyanya-style: - template_redirect@1 + is_404() trigger - get_posts(name=$slug, post_type=page, status=[private,publish]) - match candidate.ID against page_unic[i].page_new - 301 to /<town>/<orig-canonical-path>/ Closes Gitea issue #1. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
97 lines
2.7 KiB
PHP
97 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,
|
|
'suppress_filters' => false,
|
|
]);
|
|
if (empty($candidates)) {
|
|
return;
|
|
}
|
|
|
|
$candidate_id = (int) $candidates[0]->ID;
|
|
|
|
if (!\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 === '') {
|
|
return;
|
|
}
|
|
$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;
|
|
}
|
|
}
|