Compare commits

11 Commits

Author SHA1 Message Date
930b7e0534 fix: paginated region/city pages, no routes before first save, safer structure save
- Add /{slug}/page/N/ rules and keep the page number through 301s
- Route only regions synced to a term, so unsaved presets never claim /europe/ etc.
- Flush rewrites on the request after activation so structure routes survive
- Suggest the existing term slug for new cities (keeps live /tour-destination/ URLs)
- Refuse saves without the editor sentinel; confirm before saving an empty structure
- Show term-sync failures to the admin instead of reporting success

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-29 15:33:01 +03:30
f5c4c89f1a chore: bump viator-collector to 1.9.0, theme to 1.0.9; rebuild zips
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-29 15:24:34 +03:30
c73189f2db feat(menu): list regions and cities in the header menu
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-29 15:24:15 +03:30
f6153376f9 feat(display): region landing page with city grid
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-29 15:23:40 +03:30
8b70ae9104 feat(routing): region/city/product URLs with 301s from old paths
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-29 15:22:59 +03:30
9c707b7075 feat(structure): admin screen with validated save and term sync
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-29 15:22:26 +03:30
02b6ce0ff4 feat(import): store primary destination; crawl configured cities
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-29 15:20:29 +03:30
614ea98825 feat(structure): add region/city structure model with validation
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-29 15:19:49 +03:30
cfa23b6384 docs: region/city URL design and plan
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-29 15:18:26 +03:30
vargha1
eeb759f4bf sydney image pos fix 2026-10-14 13:12:03 +03:30
vargha1
3f25d5e828 css fix 2026-10-14 12:55:04 +03:30
23 changed files with 1929 additions and 19 deletions

Binary file not shown.

View File

@@ -54,5 +54,12 @@ function hoho_nav_fallback() {
echo '<ul class="nav__list">';
echo '<li><a class="nav__link" href="' . esc_url( home_url( '/' ) ) . '">' . esc_html__( 'Home', 'hoponhopoff' ) . '</a></li>';
echo '<li><a class="nav__link" href="' . esc_url( $archive ) . '">' . esc_html__( 'Tours', 'hoponhopoff' ) . '</a></li>';
// Regions + cities from the Viator Collector structure, when active.
if ( class_exists( 'VC_Menu' ) ) {
$items = VC_Menu::items();
if ( $items ) {
echo walk_nav_menu_tree( $items, 2, (object) array( 'walker' => new Hoho_Nav_Walker() ) ); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
}
}
echo '</ul>';
}

View File

@@ -4,7 +4,7 @@ Theme URI: https://git.kaamyab.dev/vargha/TourWebsite
Description: Astra child theme that replaces the Astra header and footer with the "Hop On Hop Off" design. Pairs with the Viator Collector plugin.
Author: Amir Bagheri
Template: astra
Version: 1.0.8
Version: 1.0.9
Text Domain: hoponhopoff
*/

View File

@@ -9,7 +9,7 @@
* was produced ships to the client.
*
* Exclusion rule (keep in sync with the "no docs/AI files in zips" preference):
* - any path segment: .git, .claude, .github, docs, build, node_modules
* - any path segment: .git, .claude, .github, docs, build, node_modules, tests
* - any *.md file
* - dotfiles at any level except .htaccess
*/
@@ -22,7 +22,7 @@ if ( '' === $src || '' === $out || ! is_dir( $src ) ) {
exit( 1 );
}
$excluded_dirs = array( '.git', '.claude', '.github', 'docs', 'build', 'node_modules' );
$excluded_dirs = array( '.git', '.claude', '.github', 'docs', 'build', 'node_modules', 'tests' );
function is_excluded( $rel, array $excluded_dirs ) {
$parts = explode( '/', $rel );

View File

@@ -1715,7 +1715,6 @@ dd {
grid-template-rows: 1fr;
}
.acc__a > * {
.acc__a > * {
overflow: hidden;
}
@@ -2857,7 +2856,7 @@ dd {
.hero-tour__figure--sydney {
left: 1.05em;
top: 0.35em;
top: 0;
height: 2.3em;
scale: 1;
}
@@ -3569,11 +3568,6 @@ dd {
border-color: var(--c-black);
}
white);
border-color: var(--c-black);
background: var(--c-black);
}
/* --- reviews --- */
.reviews {
display: flex;

Binary file not shown.

View File

@@ -0,0 +1,181 @@
/**
* Settings → Viator Structure editor. Regions and cities are plain DOM
* blocks; cities can only be added from the Viator destination search, and
* indexed field names are assigned on submit.
*/
(function () {
'use strict';
var cfg = window.vcStructure || {};
var i18n = cfg.i18n || {};
var form = document.getElementById('vc-structure-form');
var list = document.getElementById('vc-regions');
if (!form || !list) {
return;
}
function slugify(s) {
return String(s).toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-+|-+$/g, '');
}
function fromTemplate(id) {
var tpl = document.getElementById(id);
return tpl.content.firstElementChild.cloneNode(true);
}
function usedIds() {
var ids = {};
list.querySelectorAll('.vc-city [data-f="id"]').forEach(function (input) {
ids[input.value] = true;
});
return ids;
}
function move(el, dir) {
if (dir < 0 && el.previousElementSibling) {
el.parentNode.insertBefore(el, el.previousElementSibling);
} else if (dir > 0 && el.nextElementSibling) {
el.parentNode.insertBefore(el.nextElementSibling, el);
}
}
function addCity(region, item) {
var row = fromTemplate('vc-tpl-city');
row.querySelector('[data-f="id"]').value = item.id;
row.querySelector('[data-f="name"]').value = item.name;
row.querySelector('[data-f="slug"]').value = item.slug || slugify(item.name);
row.querySelector('.vc-city__name').textContent = item.name;
row.querySelector('.vc-city__id').textContent = item.id;
region.querySelector('.vc-cities tbody').appendChild(row);
}
function search(region) {
var q = region.querySelector('.vc-city-search input[type="search"]');
var out = region.querySelector('.vc-results');
out.textContent = i18n.searching || '…';
var data = new FormData();
data.append('action', 'vc_search_destinations');
data.append('_ajax_nonce', cfg.nonce);
data.append('q', q.value);
fetch(cfg.ajaxUrl, { method: 'POST', credentials: 'same-origin', body: data })
.then(function (r) { return r.json(); })
.then(function (res) {
if (!res || !res.success) {
out.textContent = (res && res.data && res.data.message) || i18n.failed;
return;
}
if (!res.data.results.length) {
out.textContent = i18n.noMatches;
return;
}
var used = usedIds();
out.innerHTML = '';
res.data.results.forEach(function (item) {
var row = document.createElement('div');
var btn = document.createElement('button');
btn.type = 'button';
btn.className = 'button button-small';
if (used[item.id]) {
btn.disabled = true;
btn.textContent = i18n.used;
} else {
btn.textContent = i18n.add;
btn.addEventListener('click', function () {
addCity(region, item);
out.innerHTML = '';
q.value = '';
});
}
var label = document.createElement('span');
label.textContent = item.name + ' (ID ' + item.id + ')';
row.appendChild(btn);
row.appendChild(label);
out.appendChild(row);
});
})
.catch(function () { out.textContent = i18n.failed; });
}
list.addEventListener('click', function (e) {
var btn = e.target.closest('[data-act]');
if (!btn) {
return;
}
var region = btn.closest('.vc-region');
var city = btn.closest('.vc-city');
var target = city || region;
switch (btn.getAttribute('data-act')) {
case 'up': move(target, -1); break;
case 'down': move(target, 1); break;
case 'remove-city': city.remove(); break;
case 'remove-region':
if (window.confirm(i18n.confirm)) {
region.remove();
}
break;
case 'search': search(region); break;
}
});
list.addEventListener('keydown', function (e) {
if (e.key === 'Enter' && e.target.matches('.vc-city-search input[type="search"]')) {
e.preventDefault();
search(e.target.closest('.vc-region'));
}
});
// Suggest a region slug from its name until the slug is edited by hand.
list.addEventListener('input', function (e) {
var input = e.target;
if (input.matches('.vc-region__head [data-f="slug"]')) {
input.dataset.touched = '1';
}
if (input.matches('.vc-region__head [data-f="name"]')) {
var slug = input.closest('.vc-region__head').querySelector('[data-f="slug"]');
if (!slug.dataset.touched && (slug.value === '' || slug.dataset.auto === '1')) {
slug.value = slugify(input.value);
slug.dataset.auto = '1';
}
}
});
document.getElementById('vc-add-region').addEventListener('click', function () {
var region = fromTemplate('vc-tpl-region');
list.appendChild(region);
region.querySelector('[data-f="name"]').focus();
});
function hidden(name) {
var input = document.createElement('input');
input.type = 'hidden';
input.name = name;
input.value = '1';
form.appendChild(input);
}
form.addEventListener('submit', function (e) {
var regions = list.querySelectorAll('.vc-region');
if (!regions.length) {
if (!window.confirm(i18n.confirmEmpty)) {
e.preventDefault();
return;
}
hidden('vc_confirm_empty');
}
// Proves the editor ran: the server refuses a save without it, so a
// failed script can never submit an empty structure by accident.
hidden('vc_structure_present');
regions.forEach(function (region, i) {
region.querySelectorAll('.vc-region__head [data-f]').forEach(function (input) {
input.name = 'vc_structure[' + i + '][' + input.dataset.f + ']';
});
region.querySelectorAll('.vc-city').forEach(function (city, j) {
city.querySelectorAll('[data-f]').forEach(function (input) {
input.name = 'vc_structure[' + i + '][cities][' + j + '][' + input.dataset.f + ']';
});
});
});
});
})();

View File

@@ -0,0 +1,293 @@
# Region / City / Product URLs Implementation Plan
> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
**Goal:** Serve regions at `/{region}/`, cities at `/{city}/` and products at `/{city}/{product}/`. The client manages the region → city structure from a validated settings screen.
**Architecture:** A pure-PHP `VC_Structure` class holds the structure, validation, canonical-city choice and rewrite-rule generation, and is unit-tested without WordPress. Thin WordPress layers sit on top of it:
- `VC_Structure_Admin`: settings screen, save, sync to `viator_destination` terms
- `VC_Routing`: rewrite rules, link filters, 301s
- `VC_Menu`: region items in the header menu
These layers are verified by `php -l` and a manual QA pass on a WordPress install.
**Tech Stack:** WordPress, PHP 8 (local CLI is PHP 8.4), plugin `viator-collector`, child theme `astra-child-hoponhopoff`. No Composer/PHPUnit: tests use a tiny runner at `viator-collector/tests/run.php`.
**Spec:** `viator-collector/docs/superpowers/specs/2026-10-29-region-city-urls-design.md`
## Global Constraints
- Preset regions, in order: UK `uk`, Europe `europe`, Asia `asia`, Middle East and Africa `middle-east-and-africa`, Americas `americas`, Australasia `australasia`.
- Valid slug: `^[a-z0-9]+(?:-[a-z0-9]+)*$`.
- Reserved slugs: `wp-admin`, `wp-content`, `wp-includes`, `wp-json`, `feed`, `page`, `search`, `tag`, `category`, `author`, `tours`, `tour-destination`, `tour-tag`, `tour-category`, `blog`, `about`, `contact`, `faq`, `embed`, `attachment`.
- Term meta: region flag `_vc_region` = `1`; city link `_vc_viator_destination_id` (already exists).
- Post meta: `_vc_primary_destination` (Viator destination ref string).
- Options: `vc_structure` (structure array), `vc_flush_rewrite` (flag).
- All redirects are 301 and keep the query string.
- Match plugin style: static classes, `VC_` prefix, tabs, `vc_get_option`, `VC_Logger`, text domain `viator-collector`.
- Work on branch `feature/region-city-urls`, not `main`.
- `tests/` and `docs/` never ship in the zip.
**Structure array shape** (used everywhere):
```php
array(
array(
'name' => 'Europe',
'slug' => 'europe',
'term_id' => 12, // 0 until synced
'cities' => array(
array( 'id' => '737', 'name' => 'Amsterdam', 'slug' => 'amsterdam' ),
),
),
)
```
## Review Focus
1. A city slug equal to an **unconfigured** existing destination term's slug (e.g. two Viator "Victoria"s) must be a validation error, not a silent `wp_update_term` failure. Covered by `test_validate_taken_slug` (Task 1).
2. A product whose Viator primary destination is not configured but which belongs to two configured cities must use the first city in settings order. Covered by `test_canonical_city_fallback_order` (Task 1).
3. A product in no configured city keeps `/tours/{slug}/`: `canonical_city()` returns `''`. Covered by `test_canonical_city_none` (Task 1).
4. An admin-typed slug like `New York` or `amsterdam!` must be rejected, not silently changed. Covered by `test_validate_bad_slug` (Task 1).
5. Filter and sort query strings (`?dest=…&sort=…&paged=2`) must survive every 301. Covered by manual check M6 (Task 7).
---
### Task 1: `VC_Structure` core and test runner
**Files:**
- Create: `viator-collector/includes/class-vc-structure.php`
- Create: `viator-collector/tests/run.php`, `viator-collector/tests/test-structure.php`
- Modify: `build-zip.php` (add `'tests'` to `$excluded_dirs`)
**Interfaces (Produces):** class `VC_Structure`, all `public static`:
- `const OPTION = 'vc_structure';`
- `default_regions(): array`: the six presets, `term_id` 0, no cities.
- `get(): array`: `get_option( self::OPTION, self::default_regions() )`, cached in a static per request. Untested; WordPress only.
- `normalize( array $raw ): array`
- Shape POST data into the structure shape: trim names, `trim(strtolower())` slugs, cast `term_id` to int and `id` to a digit string, drop city rows with an empty `id`, reindex.
- An empty region slug becomes `slugify( name )`. An empty city slug becomes `slugify( city name )`.
- `slugify( string $s ): string`: lowercase, runs of non `[a-z0-9]` become `-`, trim `-`.
- `reserved_slugs(): array`: the list in Global Constraints.
- `validate( array $structure, array $destination_map, array $taken ): array`
- `$destination_map` is Viator `id => name`. `$taken` is `slug => human label` for slugs owned by something outside the structure.
- Returns a list of error strings, empty when valid. Messages are exact:
- `Region %d has no name.` (1-based)
- `City ID %s is not a Viator destination.`
- `%s is listed more than once.` (city name)
- `Slug "%s" is invalid: use only a-z, 0-9 and -.`
- `Slug "%s" is reserved.`
- `Slug "%s" is used more than once.`
- `Slug "%s" is already used by %s.`
- `cities( array $structure ): array`: ordered `viator_id => city + array( 'region' => region slug )`.
- `canonical_city( array $structure, array $dest_ids, string $primary_id ): string`
- Returns the city slug for `$primary_id` if it is configured.
- Otherwise returns the slug of the first configured city (in `cities()` order) that appears in `$dest_ids`.
- Otherwise returns `''`.
- `primary_destination_id( array $destinations ): string`: `ref` (or `destinationId`) of the entry with truthy `primary`, else `''`.
- `rewrite_rules( array $structure ): array`, regex => query, in this order:
- each region: `'^europe/?$' => 'index.php?viator_destination=europe'`
- each city: `'^amsterdam/?$' => 'index.php?viator_destination=amsterdam'` and `'^amsterdam/([^/]+)/?$' => 'index.php?viator_tour=$matches[1]'`
- [ ] **Step 1: Write the runner.** `tests/run.php` defines `ABSPATH`, requires `includes/class-vc-structure.php` and every `tests/test-*.php`, then calls each function whose name starts with `test_`. It provides `vc_assert_same( $expected, $actual, string $msg )`, which throws on mismatch, and `vc_assert_contains( string $needle, array $errors )`. It prints `N passed, M failed` and exits 1 on any failure.
- [ ] **Step 2: Write the failing tests** in `tests/test-structure.php`. Use the fixture `$s` = Europe(`amsterdam` id 737, `paris` id 479) + Americas(`boston` id 678) and `$map = array('737'=>'Amsterdam','479'=>'Paris','678'=>'Boston','22'=>'Victoria')`.
```php
test_default_regions // 6 regions; slugs exactly the Global Constraints list, in order
test_normalize_fills_slugs // region name 'Middle East and Africa', slug '' -> 'middle-east-and-africa'; city row with id '' dropped
test_validate_ok // validate($s,$map,[]) === []
test_validate_unknown_city // city id '999' -> contains 'City ID 999 is not a Viator destination.'
test_validate_duplicate_city // 737 in Europe and Americas -> contains 'Amsterdam is listed more than once.'
test_validate_duplicate_slug // region slug 'paris' + city 'paris' -> contains 'Slug "paris" is used more than once.'
test_validate_bad_slug // 'New York' and 'amsterdam!' -> both 'Slug "…" is invalid: use only a-z, 0-9 and -.'
test_validate_reserved // city slug 'contact' -> contains 'Slug "contact" is reserved.'
test_validate_taken_slug // $taken=['victoria'=>'destination "Victoria"'], city slug 'victoria' -> contains 'Slug "victoria" is already used by destination "Victoria".'
test_validate_empty_region // region name '' -> contains 'Region 1 has no name.'
test_canonical_city_primary // canonical_city($s,['479','737'],'479') === 'paris'
test_canonical_city_fallback_order // canonical_city($s,['678','479','737'],'5555') === 'amsterdam'
test_canonical_city_none // canonical_city($s,['5555'],'') === ''
test_primary_destination_id // [['ref'=>'1'],['ref'=>'2','primary'=>true]] -> '2'; [] -> ''
test_rewrite_rules // exact array: europe, americas, amsterdam, amsterdam product, paris, paris product, boston, boston product (region rules first, then cities)
test_rewrite_rules_empty_region // region with no cities still yields '^europe/?$'
```
- [ ] **Step 3: Run and confirm the failure.** Run `php tests/run.php` from `viator-collector/`. Expected: a fatal error saying class `VC_Structure` was not found.
- [ ] **Step 4: Implement `VC_Structure`** with the interface above. Only `get()` may call WordPress functions.
- [ ] **Step 5: Run and confirm the pass.** Run `php tests/run.php`. Expected: `16 passed, 0 failed`.
- [ ] **Step 6: Exclude tests from the zip.** Add `'tests'` to `$excluded_dirs` in `build-zip.php`. Then run `php build-zip.php viator-collector "$TMP/vc.zip"` and confirm no `tests/` entries are in the zip.
- [ ] **Step 7: Commit.** Commit message: `feat(structure): add region/city structure model with validation`.
### Task 2: Importer stores the primary destination; crawl follows the structure
**Files:**
- Modify: `viator-collector/includes/class-vc-importer.php` (the `$meta` array in `save_tour_meta`, ~line 370)
- Modify: `viator-collector/includes/class-vc-cron.php` (`start_run`, ~lines 159-166)
- Modify: `viator-collector/includes/class-vc-settings.php` (description of the crawl destinations field)
- Modify: `viator-collector/includes/class-vc-plugin.php` (load `class-vc-structure.php` before the importer)
**Interfaces (Consumes):** `VC_Structure::primary_destination_id()`, `VC_Structure::cities()`, `VC_Structure::get()`.
- [ ] **Step 1: Store the primary destination.** Add `'_vc_primary_destination' => VC_Structure::primary_destination_id( (array) vc_array_get( $product, 'destinations', array() ) )` to the `$meta` array.
- [ ] **Step 2: Build the crawl queue from the structure.** In `start_run`:
- If `array_keys( VC_Structure::cities( VC_Structure::get() ) )` is non-empty, the queue is exactly that list.
- Otherwise keep the existing allowlist/full-catalogue logic.
- Log `Sync run started from structure — %d cities queued.` in the structure case.
- [ ] **Step 3: Relabel the old allowlist.** Append `Used only when no cities are set on the Viator Structure screen.` to the crawl destinations field's description.
- [ ] **Step 4: Lint.** Run `php -l` on each changed file. Expected: `No syntax errors detected` for each. Then run `php tests/run.php`, which should still pass.
- [ ] **Step 5: Commit.** Commit message: `feat(import): store primary destination; crawl configured cities`.
### Task 3: Structure settings screen, validated save, and term sync
**Files:**
- Create: `viator-collector/includes/class-vc-structure-admin.php`
- Create: `viator-collector/assets/js/vc-structure-admin.js`
- Modify: `viator-collector/includes/class-vc-plugin.php` (load the file and call `VC_Structure_Admin::init()`)
**Interfaces:**
- Consumes: all of `VC_Structure`; existing AJAX action `vc_search_destinations` (nonce `vc_search_destinations`, POST `q`, returns `{results:[{id,name}]}`); `VC_Taxonomies::get_or_create_destination_by_id( $id, $name )`; `VC_API::get_destination_map()`.
- Produces:
- `VC_Structure_Admin::init()`
- `VC_Structure_Admin::taken_slugs( array $structure ): array`, slug => label
- `VC_Structure_Admin::sync_terms( array $old, array $new ): array`, returns `$new` with region `term_id`s filled
- Sets option `vc_flush_rewrite` = 1 after a successful save
- [ ] **Step 1: Add the screen.** Register a submenu under Settings with `add_options_page`: title `Viator Structure`, slug `viator-collector-structure`, capability `manage_options`.
- The page renders one block per region: name input, slug input, a hidden `term_id`, and up/down/remove buttons.
- Each region block holds its city rows. A city row shows the name read-only, an editable slug, and a hidden `id` and `name`, with up/down/remove buttons.
- Each region has a city search box that calls `vc_search_destinations`. Results whose id is already used anywhere in the form are shown disabled.
- An "Add region" button sits at the end.
- Field names: `vc_structure[i][name|slug|term_id]` and `vc_structure[i][cities][j][id|name|slug]`. The JS renumbers indexes before submit.
- The form posts to `admin-post.php`, action `vc_save_structure`, nonce `vc_save_structure`.
- [ ] **Step 2: Implement `taken_slugs( $structure )`.** It returns these as `slug => label`:
- top-level Pages (`post_parent` 0), labelled `page "Title"`
- posts of every public post type in any status except trash and auto-draft, labelled `post "Title"`
- `viator_destination` terms that are neither a structure region (`term_id`) nor a structure city (matched through `_vc_viator_destination_id`), labelled `destination "Name"`
- [ ] **Step 3: Implement the save handler.**
1. Check the capability and nonce.
2. Run `normalize( wp_unslash( $_POST['vc_structure'] ?? array() ) )`.
3. Load the destination map. If that returns a `WP_Error`, treat it as the single error `Could not load Viator destinations; nothing was saved.`
4. Run `validate( $s, $map, self::taken_slugs( $s ) )`.
5. On errors, store `array( 'errors' => …, 'structure' => $s )` in transient `vc_structure_draft_{user_id}` (10 minutes) and redirect back. The screen re-renders that draft with a red notice listing every error. Nothing is saved.
6. On success: `$s = self::sync_terms( VC_Structure::get(), $s )`, then `update_option( VC_Structure::OPTION, $s )`, then `update_option( 'vc_flush_rewrite', 1 )`, then redirect with the notice `Structure saved.`
- [ ] **Step 4: Implement `sync_terms( $old, $new )`.**
- **Region:** update the term by `term_id` if it exists (name, slug, parent 0). Otherwise `wp_insert_term( name, 'viator_destination', array( 'slug' => slug ) )`. In both cases set `_vc_region` = 1 and store the `term_id` back.
- **City:** `$tid = VC_Taxonomies::get_or_create_destination_by_id( id, name )`, then `wp_update_term( $tid, 'viator_destination', array( 'slug' => slug, 'parent' => region term_id ) )`.
- **Removed regions** (old `term_id`s that are no longer present): `wp_delete_term`.
- **Removed cities** (old ids that are no longer present): set `parent` to 0.
- Log every `WP_Error` with `VC_Logger::error`.
- [ ] **Step 5: Add the page-slug clash notice.** On `admin_notices`, on the page edit screen, if the current page's `post_name` is a structure region or city slug, show the warning `This page's URL is also used by the Viator region/city "%s"; the Viator page will take priority.`
- [ ] **Step 6: Lint.** Run `php -l includes/class-vc-structure-admin.php` and `node --check assets/js/vc-structure-admin.js`. Expected: no errors.
- [ ] **Step 7: Commit.** Commit message: `feat(structure): admin screen with validated save and term sync`.
### Task 4: Routing — rewrite rules, links, redirects
**Files:**
- Create: `viator-collector/includes/class-vc-routing.php`
- Modify: `viator-collector/includes/class-vc-plugin.php` (load the file and call `VC_Routing::init()`)
**Interfaces:**
- Consumes: `VC_Structure::get()`, `::rewrite_rules()`, `::cities()`, `::canonical_city()`; option `vc_flush_rewrite`.
- Produces: `VC_Routing::init()`, `VC_Routing::is_configured_term( WP_Term $term ): bool`, `VC_Routing::product_city( int $post_id ): string`
- [ ] **Step 1: Register the rules.** On `init` at priority 20, call `add_rewrite_rule( $regex, $query, 'top' )` for each `rewrite_rules( get() )` entry. Then, if `get_option( 'vc_flush_rewrite' )` is set, delete it and call `flush_rewrite_rules( false )`.
- [ ] **Step 2: Implement `is_configured_term`.** It is true when the term is in `viator_destination` and either has `_vc_region` = 1 or its `_vc_viator_destination_id` is a key of `cities()`.
- [ ] **Step 3: Implement `product_city`.** Build `$dest_ids` from the `ref` / `destinationId` values in the post's `_vc_destinations` JSON meta. Return `canonical_city( get(), $dest_ids, (string) _vc_primary_destination )`. Cache the result per `post_id` in a static.
- [ ] **Step 4: Add the link filters.**
- `term_link`: for a configured term, return `home_url( '/' . $term->slug . '/' )`.
- `post_type_link`: for a `viator_tour` with a non-empty `post_name` and a non-empty `product_city`, return `home_url( "/{city}/{post_name}/" )`.
- Everything else is returned unchanged.
- [ ] **Step 5: Add the 301s.** On `template_redirect`, for `is_singular( 'viator_tour' )` (published, not a preview) and for configured `is_tax( 'viator_destination' )`:
- Compute the canonical URL (`get_permalink()` / `get_term_link()`).
- Compare `untrailingslashit` paths of the canonical URL and `REQUEST_URI` with the query string removed.
- If they differ, `wp_safe_redirect( canonical + '?' + original query string if any, 301 )` and exit.
- [ ] **Step 6: Add the term canonical tag.** On `wp_head`, for a configured term archive, print `<link rel="canonical" href="…">`. Skip this when `WPSEO_VERSION` or `RANK_MATH_VERSION` is defined. Singular products already get core's canonical from `get_permalink()`.
- [ ] **Step 7: Lint and commit.** Run `php -l includes/class-vc-routing.php`. Expected: no errors. Commit message: `feat(routing): region/city/product URLs with 301s from old paths`.
### Task 5: Region landing page
**Files:**
- Create: `viator-collector/templates/region.php`
- Modify: `viator-collector/includes/class-vc-display.php` (`taxonomy_template`, ~line 534)
- Modify: `viator-collector/templates/listing.php` (new optional arg `$vc_after_hero`)
**Interfaces (Consumes):** `VC_Routing::is_configured_term()`; existing `vc_get_template()`, `card-destination.php` (arg `term`), `listing.php`.
- [ ] **Step 1: Route region terms.** In `taxonomy_template`, when the queried term has `_vc_region` = 1, return `get_stylesheet_directory() . '/viator-collector/region.php'` if it exists, else `VC_PLUGIN_DIR . 'templates/region.php'`.
- [ ] **Step 2: Add `$vc_after_hero` to `listing.php`.** It is an optional HTML string, default `''`, echoed immediately after the listing hero section closes.
- [ ] **Step 3: Write `templates/region.php`.**
- Copy the structure of `taxonomy-viator.php`.
- Build `$vc_after_hero` as `<section class="vc-section vc-section--destinations">`. It holds the heading `Cities in %s` and a `vc-destination-grid` of `card-destination.php` cards.
- The cards are the child terms from `get_terms( array( 'taxonomy' => 'viator_destination', 'parent' => term_id, 'hide_empty' => false ) )`, ordered as in the structure (the order of `cities()`).
- The listing's main query already includes child terms, so it shows every tour in the region.
- [ ] **Step 4: Lint and commit.** Run `php -l` on the three files. Commit message: `feat(display): region landing page with city grid`.
### Task 6: Regions in the header menu
**Files:**
- Create: `viator-collector/includes/class-vc-menu.php`
- Modify: `viator-collector/includes/class-vc-plugin.php` (load the file and call `VC_Menu::init()`)
- Modify: `astra-child-hoponhopoff/inc/nav-walker.php` (`hoho_nav_fallback`)
**Interfaces:**
- Consumes: `VC_Structure::get()`; region and city terms (`term_id`, links via `get_term_link`).
- Produces: `VC_Menu::items(): array` of menu-item objects.
- [ ] **Step 1: Implement `VC_Menu::items()`.** Build `stdClass` items with these fields: `ID`, `db_id`, `menu_item_parent` (string), `title`, `url`, `classes` (array), `type` `'custom'`, `object` `'custom'`, `object_id`, `target` `''`, `xfn` `''`, `attr_title` `''`, `description` `''`, `current` false.
- Use negative unique `ID`/`db_id`: `-1000 - n`.
- Each region gets a top-level item.
- A region with cities gets these children, in order: `All of %s` (the region URL, because the theme walker turns a parent with children into a toggle button with no link), then one item per city.
- Regions whose term no longer exists are skipped.
- [ ] **Step 2: Append to the header menu.** Add the filter `wp_nav_menu_objects` (`$items`, `$args`). When `$args->theme_location === 'hoho_primary'`, return `array_merge( $items, self::items() )`. Set `menu_order` sequentially after the existing items.
- [ ] **Step 3: Update the theme fallback.** In `hoho_nav_fallback`, after the Tours link and when `class_exists( 'VC_Menu' )`, echo `walk_nav_menu_tree( VC_Menu::items(), 2, (object) array( 'walker' => new Hoho_Nav_Walker() ) )` inside the same `<ul>`.
- [ ] **Step 4: Lint and commit.** Run `php -l` on both PHP files. Commit message: `feat(menu): list regions and cities in the header menu`.
### Task 7: Version bump, build, and manual QA
**Files:**
- Modify: `viator-collector/viator-collector.php` (Version header and `VC_VERSION` → `1.9.0`)
- [ ] **Step 1: Bump the version, run the tests and build the zips.**
- Bump the version to 1.9.0.
- Run `php tests/run.php`. Expected: all tests pass.
- From the repo root, run `php build-zip.php viator-collector viator-collector.zip`.
- [ ] **Step 2: Manual QA on a WordPress install** with the client's live data copied over. Record pass or fail for each check:
- M1. Save the preset regions and add `Boston` and `New York City` under Americas. The menu shows the six regions, and Americas drops down to `All of Americas`, Boston and New York City.
- M2. `/americas/` shows the city grid and all of their tours. `/boston/` lists Boston tours.
- M3. `/tour-destination/boston/` gives a 301 to `/boston/`. Do the same check for all 15 of the client's URLs once those cities are added.
- M4. A Boston tour's card links to `/boston/{slug}/`. `/tours/{slug}/` and `/new-york-city/{slug}/` both give a 301 to it.
- M5. Saving each of these shows an error, and the previous structure is unchanged:
- a city twice
- slug `contact`
- slug `New York`
- a city slug equal to an existing page's slug
- M6. `/boston/?sort=price_asc&paged=2` keeps its query. `/tour-destination/boston/?sort=price_asc` gives a 301 to `/boston/?sort=price_asc`.
- M7. Run a manual sync. The log reads `cities queued` with the configured count.
- M8. `/contact/` and other pages still load.
- [ ] **Step 3: Commit.** Commit message: `chore: bump viator-collector to 1.9.0`.

View File

@@ -0,0 +1,159 @@
# Region / City / Product URL Structure — Design
Date: 2026-10-29
Status: draft, awaiting approval
## Intent
The client wants the site organised by place, like hoponhopoffplus.com:
visitors pick a **region**, then a **city**, then a **product**. URLs should
read the same way:
| Page | URL | Example |
|---------|---------------------------------------|----------------------------------------------------------------|
| Region | `/{region-slug}/` | `/europe/` |
| City | `/{city-slug}/` | `/amsterdam/` |
| Product | `/{city-slug}/{product-slug}/` | `/amsterdam/city-sightseeing-hop-on-hop-off-amsterdam-bus-tour-24-hours/` |
The header menu lists the regions: **UK, Europe, Asia, Middle East and
Africa, Americas, Australasia**.
## Goals
- The client builds the region → city structure in the plugin settings.
- Products keep importing automatically from Viator. A city page shows
**every** Viator product in that city, not only hop-on hop-off tours.
- The settings screen makes bad data impossible to save (see Validation).
- Existing live URLs keep working through 301 redirects. The client sent
these, which are live today and likely the first Americas cities:
washington-dc, boston, chicago, new-york-city, new-orleans, miami,
las-vegas, los-angeles, san-diego, san-francisco, seattle, victoria,
vancouver, montreal, toronto (all under `/tour-destination/{slug}/`).
## Non-goals
- The new static pages from `new front/` (about, contact, faq, blog,
blog-post). That is a separate, later project.
- A hand-built sample product page. Products come from the Viator plugin.
- Redesigning the listing, card or single-tour templates.
- Region in the city URL (`/europe/amsterdam/`). The client's examples
rule this out.
## Anti-goals (would count as failure even if it "works")
- A city or region URL that hijacks an existing WordPress page, post or
system path (e.g. a city slugged `about` or `wp-admin`).
- The same product reachable at two indexable URLs (duplicate content).
- Any of the client's existing `/tour-destination/...` links returning 404.
- Admin able to type a city that does not exist in Viator.
## Decisions (agreed in conversation)
- Structure lives in plugin settings; client owns it.
- Cities are picked only from Viator's destination list (reuse the existing
`vc_search_destinations` AJAX lookup in `class-vc-settings.php`).
- A product that belongs to several configured cities **appears on every
one of those city pages**.
- Old `/tour-destination/{slug}/` URLs 301 to `/{slug}/`.
## Decisions made by Claude (user delegated URL choices)
1. **One canonical product URL.** City in the URL = the product's Viator
*primary* destination if that destination is a configured city;
otherwise the first configured city (in settings order) the product
belongs to. Requesting the product under any other city
(`/paris/same-tour/`) 301s to the canonical URL. `/tours/{slug}/`
also 301s to the canonical URL.
2. **Products in no configured city** (left over from older crawls) keep
`/tours/{slug}/` and do not appear on any region/city page.
3. **Data model: reuse the `viator_destination` taxonomy (hierarchical).**
- Region = top-level term with no Viator ID, marked by term meta
`_vc_region = 1`.
- City = term linked to a Viator destination ID (existing
`_vc_viator_destination_id` meta), with its parent set to its region.
- Existing city terms are reused by Viator ID, so current slugs such as
`washington-dc` are kept as-is.
- A region page queries its child terms with `include_children`, so it
lists every product in its cities without extra assignment.
- The structure itself is stored as one option (`vc_structure`): an
ordered list of regions, each with an ordered list of
`{viator_id, name, slug}` cities. Saving the settings syncs it into
terms (create/re-parent/rename), never deleting products.
4. **The six regions come preset** (slugs: `uk`, `europe`, `asia`,
`middle-east-and-africa`, `americas`, `australasia`). The client can
rename, reorder, add or remove regions.
5. **City slug** defaults to `sanitize_title( Viator name )`, or the
existing term's slug if one exists. The admin may edit it; edits go
through the same validation.
6. **Routing: explicit rewrite rules per configured slug, not catch-alls.**
For each region and city, add rules for `^{slug}/?$`; for each city also
`^{slug}/([^/]+)/?$` → product. Rules are rebuilt and flushed when the
structure is saved. Unconfigured paths fall through to normal WordPress
routing, so pages like `/contact/` are unaffected. Listing pagination
already uses `?paged=`, so no `/page/N/` rule is needed (the builder
should confirm this).
7. **Links.** `term_link` filter returns `/{slug}/` for region and city
terms; `post_type_link` filter returns the canonical product URL.
Unconfigured destination terms keep `/tour-destination/{slug}/`.
8. **Crawl.** When the structure has at least one city, the crawl queue is
exactly the configured cities' Viator IDs. The old
`crawl_destinations` allowlist is used only when the structure is empty,
and its field is labelled as such.
9. **Primary destination.** The importer stores the Viator primary
destination ref (the entry in `destinations` with `primary: true`) in
post meta `_vc_primary_destination`. Products imported before this change
get it on the next sync; until then the fallback rule in (1) applies.
10. **Menu.** Regions are added automatically to the "HoHo — Header Menu"
location as top-level items, each with a dropdown of its cities (the
existing nav walker already renders dropdowns). Items the client added
by hand in the menu stay, and the regions are appended after them.
11. **Region landing page.** Hero (region name and term image), a grid of
its city cards (reuse `card-destination.php`), then the standard
listing of all tours in the region. **City landing page** = the
existing taxonomy listing template, unchanged apart from the URLs.
12. **SEO.** Canonical tags follow the canonical URLs above. All redirects
are 301.
## Validation (settings save)
The whole save is rejected, with the previous structure kept, and the admin
sees a list of every problem, if any of these is true:
- A city's Viator ID is not in Viator's destination list.
- The same city (Viator ID) appears twice, in one region or across regions.
- Two items (regions or cities) share a slug.
- A region has an empty name.
- A slug is empty or contains anything other than `a-z`, `0-9` and `-`.
- A slug collides with an existing page, post, or other public post-type
slug or archive (`tours`), or with a reserved word: WordPress reserved
query vars, `wp-admin`, `wp-content`, `wp-includes`, `feed`, `page`,
`search`, `tag`, `category`, `author`, `tour-destination`, `tour-tag`,
`tour-category`, `blog`, `about`, `contact`, `faq`.
The editor UI also prevents most of these before submit: cities are added
only from search results, and already-used cities are greyed out in the
results.
Also, when a Page is created or renamed to a slug a region or city already
uses, show an admin notice warning about the clash. (WordPress itself does
not block this.)
## Constraints
- WordPress, Astra child theme `astra-child-hoponhopoff`, plugin
`viator-collector`. Match the existing plugin style (static classes,
`VC_` prefix, `vc_get_option`, `VC_Logger`).
- Viator Basic access: the catalogue is only enumerable per destination,
which suits per-city crawling.
- No changes to how products are fetched or priced.
## Left to the builder
- Settings editor UI details (drag-to-reorder or up/down buttons, etc.)
as long as the validation and pick-from-Viator rules hold.
- Whether the structure editor is a section of the existing settings page
or its own sub-page.
- Exact redirect hook (`template_redirect` is the expected place).
- What happens to a city removed from the structure: its term stays (it is
un-parented and loses its `/{slug}/` route, so it falls back to
`/tour-destination/{slug}/`). Products are not deleted.

View File

@@ -156,10 +156,14 @@ class VC_Cron {
$map = get_transient( 'vc_destination_map' );
// A destination allowlist (comma-separated IDs) narrows the crawl to a
// focused set; empty means the whole catalogue.
// Cities configured on the Viator Structure screen define the crawl.
// Without any, a destination allowlist (comma-separated IDs) narrows
// the crawl to a focused set; empty means the whole catalogue.
$cities = array_map( 'strval', array_keys( VC_Structure::cities( VC_Structure::get() ) ) );
$allow = array_filter( array_map( 'trim', explode( ',', (string) vc_get_option( 'crawl_destinations', '' ) ) ) );
if ( ! empty( $allow ) ) {
if ( ! empty( $cities ) ) {
$queue = $cities;
} elseif ( ! empty( $allow ) ) {
$queue = array_values( array_unique( $allow ) );
} else {
$queue = is_array( $map ) ? array_keys( $map ) : array();
@@ -191,7 +195,11 @@ class VC_Cron {
);
update_option( 'vc_ingest_in_progress', 1, false );
update_option( 'vc_last_sync_started_at', current_time( 'mysql' ), false );
if ( ! empty( $cities ) ) {
VC_Logger::info( sprintf( 'Sync run started from structure — %d cities queued.', count( $queue ) ) );
} else {
VC_Logger::info( sprintf( 'Sync run started — %d destinations queued.', count( $queue ) ) );
}
return true;
}

View File

@@ -532,6 +532,10 @@ class VC_Display {
}
public static function taxonomy_template( $template ) {
if ( is_tax( 'viator_destination' ) && get_term_meta( get_queried_object_id(), '_vc_region', true ) ) {
$path = get_stylesheet_directory() . '/viator-collector/region.php';
return file_exists( $path ) ? $path : VC_PLUGIN_DIR . 'templates/region.php';
}
if ( is_tax( array( 'viator_destination', 'viator_tag', 'viator_category' ) ) ) {
$path = get_stylesheet_directory() . '/viator-collector/taxonomy-viator.php';
if ( file_exists( $path ) ) {

View File

@@ -368,6 +368,7 @@ class VC_Importer {
'_vc_cancellation_policy' => wp_json_encode( vc_first_non_empty( array( vc_array_get( $product, 'cancellationPolicy' ), vc_array_get( $product, 'cancellation' ) ), array() ) ),
'_vc_supplier' => sanitize_text_field( $supplier ),
'_vc_destinations' => wp_json_encode( vc_array_get( $product, 'destinations', array() ) ),
'_vc_primary_destination' => VC_Structure::primary_destination_id( (array) vc_array_get( $product, 'destinations', array() ) ),
'_vc_tags' => wp_json_encode( vc_array_get( $product, 'tags', array() ) ),
'_vc_rating' => sanitize_text_field( (string) $rating ),
'_vc_review_count' => absint( $review_count ),

View File

@@ -0,0 +1,88 @@
<?php
defined( 'ABSPATH' ) || exit;
/**
* Appends the Viator Structure regions (each with a dropdown of its cities)
* to the theme's header menu, so the menu follows the structure without
* hand-editing Appearance → Menus.
*/
class VC_Menu {
const LOCATION = 'hoho_primary';
public static function init() {
add_filter( 'wp_nav_menu_objects', array( __CLASS__, 'append' ), 10, 2 );
}
public static function append( $items, $args ) {
if ( empty( $args->theme_location ) || self::LOCATION !== $args->theme_location ) {
return $items;
}
$order = count( $items );
$extra = self::items();
foreach ( $extra as $item ) {
$item->menu_order = ++$order;
}
return array_merge( $items, $extra );
}
/**
* Menu-item objects for the walker. The theme walker turns a parent with
* children into a toggle button (no link), so a region's dropdown starts
* with an "All of {region}" link to the region page itself.
*
* @return object[]
*/
public static function items() {
$items = array();
$n = 0;
foreach ( VC_Structure::get() as $region ) {
$term = $region['term_id'] ? get_term( (int) $region['term_id'], 'viator_destination' ) : null;
if ( ! $term instanceof WP_Term ) {
continue;
}
$region_url = get_term_link( $term );
if ( is_wp_error( $region_url ) ) {
continue;
}
$parent = self::item( ++$n, 0, $term->name, $region_url );
$items[] = $parent;
if ( ! $region['cities'] ) {
continue;
}
/* translators: %s: region name. */
$items[] = self::item( ++$n, $parent->db_id, sprintf( __( 'All of %s', 'viator-collector' ), $term->name ), $region_url );
foreach ( $region['cities'] as $city ) {
$items[] = self::item( ++$n, $parent->db_id, $city['name'], home_url( '/' . $city['slug'] . '/' ) );
}
}
return $items;
}
private static function item( $n, $parent_id, $title, $url ) {
$id = -1000 - $n;
$item = new stdClass();
$item->ID = $id;
$item->db_id = $id;
$item->menu_item_parent = (string) $parent_id;
$item->object_id = (string) $id;
$item->object = 'custom';
$item->type = 'custom';
$item->type_label = '';
$item->title = $title;
$item->url = $url;
$item->target = '';
$item->attr_title = '';
$item->description = '';
$item->classes = array( 'menu-item', 'vc-structure-item' );
$item->xfn = '';
$item->status = 'publish';
$item->post_parent = 0;
$item->menu_order = $n;
$item->current = false;
$item->current_item_ancestor = false;
$item->current_item_parent = false;
return $item;
}
}

View File

@@ -19,6 +19,9 @@ final class VC_Plugin {
VC_CPT::init();
VC_Taxonomies::init();
VC_Settings::init();
VC_Structure_Admin::init();
VC_Routing::init();
VC_Menu::init();
VC_Cron::init();
VC_Display::init();
VC_Sections::init();
@@ -30,10 +33,14 @@ final class VC_Plugin {
'includes/class-vc-logger.php',
'includes/class-vc-cpt.php',
'includes/class-vc-taxonomies.php',
'includes/class-vc-structure.php',
'includes/class-vc-api.php',
'includes/class-vc-importer.php',
'includes/class-vc-cron.php',
'includes/class-vc-settings.php',
'includes/class-vc-structure-admin.php',
'includes/class-vc-routing.php',
'includes/class-vc-menu.php',
'includes/class-vc-display.php',
'includes/class-vc-sections.php',
);
@@ -53,6 +60,9 @@ final class VC_Plugin {
VC_Taxonomies::register();
VC_Cron::maybe_schedule();
flush_rewrite_rules();
// Structure routes are added on init, which has not run for this
// request; flush again on the next one so they are included.
update_option( 'vc_flush_rewrite', 1 );
}
public static function deactivate() {

View File

@@ -0,0 +1,147 @@
<?php
defined( 'ABSPATH' ) || exit;
/**
* Place-based URLs from the Viator Structure: /{region}/, /{city}/ and
* /{city}/{tour}/. Old /tour-destination/… and /tours/… addresses 301 to
* the new ones, and a tour opened under the wrong city 301s to its one
* canonical city.
*/
class VC_Routing {
private static $product_city = array();
public static function init() {
// After the CPT/taxonomies register (default priority 10).
add_action( 'init', array( __CLASS__, 'add_rules' ), 20 );
add_filter( 'term_link', array( __CLASS__, 'term_link' ), 10, 3 );
add_filter( 'post_type_link', array( __CLASS__, 'post_type_link' ), 10, 2 );
// Ahead of core's redirect_canonical (priority 10).
add_action( 'template_redirect', array( __CLASS__, 'redirect' ), 5 );
add_action( 'wp_head', array( __CLASS__, 'term_canonical' ), 1 );
}
public static function add_rules() {
foreach ( VC_Structure::rewrite_rules( VC_Structure::get() ) as $regex => $query ) {
add_rewrite_rule( $regex, $query, 'top' );
}
if ( get_option( 'vc_flush_rewrite' ) ) {
delete_option( 'vc_flush_rewrite' );
flush_rewrite_rules( false );
}
}
public static function is_configured_term( $term ) {
if ( ! $term instanceof WP_Term || 'viator_destination' !== $term->taxonomy ) {
return false;
}
if ( get_term_meta( $term->term_id, '_vc_region', true ) ) {
return true;
}
$viator_id = (string) get_term_meta( $term->term_id, '_vc_viator_destination_id', true );
if ( '' === $viator_id ) {
return false;
}
$cities = VC_Structure::cities( VC_Structure::get() );
return isset( $cities[ $viator_id ] );
}
/**
* Slug of the city a tour's URL lives under, or '' (it stays at /tours/).
*/
public static function product_city( $post_id ) {
$post_id = (int) $post_id;
if ( isset( self::$product_city[ $post_id ] ) ) {
return self::$product_city[ $post_id ];
}
$dest_ids = array();
$destinations = json_decode( (string) get_post_meta( $post_id, '_vc_destinations', true ), true );
foreach ( is_array( $destinations ) ? $destinations : array() as $destination ) {
$ref = is_array( $destination ) ? ( $destination['ref'] ?? ( $destination['destinationId'] ?? '' ) ) : $destination;
if ( '' !== (string) $ref ) {
$dest_ids[] = (string) $ref;
}
}
$primary = (string) get_post_meta( $post_id, '_vc_primary_destination', true );
self::$product_city[ $post_id ] = VC_Structure::canonical_city( VC_Structure::get(), $dest_ids, $primary );
return self::$product_city[ $post_id ];
}
public static function term_link( $url, $term, $taxonomy ) {
if ( 'viator_destination' === $taxonomy && self::is_configured_term( $term ) ) {
return home_url( '/' . $term->slug . '/' );
}
return $url;
}
public static function post_type_link( $url, $post ) {
if ( 'viator_tour' !== $post->post_type || '' === $post->post_name ) {
return $url;
}
$city = self::product_city( $post->ID );
if ( '' === $city ) {
return $url;
}
return home_url( '/' . $city . '/' . $post->post_name . '/' );
}
public static function redirect() {
if ( is_preview() ) {
return;
}
$canonical = '';
if ( is_singular( 'viator_tour' ) ) {
$post = get_queried_object();
if ( $post && 'publish' === $post->post_status ) {
$canonical = get_permalink( $post );
}
} elseif ( is_tax( 'viator_destination' ) ) {
$term = get_queried_object();
if ( self::is_configured_term( $term ) ) {
$canonical = get_term_link( $term );
// Keep the page: /tour-destination/x/page/2/ and /x/?paged=2
// both land on /x/page/2/ (the form core's redirect_canonical
// would produce anyway).
$paged = (int) get_query_var( 'paged' );
if ( $paged > 1 && ! is_wp_error( $canonical ) ) {
$canonical = trailingslashit( $canonical ) . 'page/' . $paged . '/';
}
}
}
if ( ! $canonical || is_wp_error( $canonical ) ) {
return;
}
$request = isset( $_SERVER['REQUEST_URI'] ) ? wp_unslash( $_SERVER['REQUEST_URI'] ) : ''; // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized
$parts = explode( '?', $request, 2 );
$current = untrailingslashit( rawurldecode( $parts[0] ) );
$target = untrailingslashit( rawurldecode( (string) wp_parse_url( $canonical, PHP_URL_PATH ) ) );
if ( $current === $target ) {
return;
}
if ( isset( $parts[1] ) && '' !== $parts[1] ) {
$canonical .= '?' . $parts[1];
$canonical = remove_query_arg( 'paged', $canonical );
}
wp_safe_redirect( $canonical, 301 );
exit;
}
/**
* Core prints rel=canonical for single tours only; add it for region and
* city archives unless an SEO plugin already handles canonicals.
*/
public static function term_canonical() {
if ( defined( 'WPSEO_VERSION' ) || defined( 'RANK_MATH_VERSION' ) || ! is_tax( 'viator_destination' ) ) {
return;
}
$term = get_queried_object();
if ( ! self::is_configured_term( $term ) ) {
return;
}
$link = get_term_link( $term );
if ( ! is_wp_error( $link ) ) {
echo '<link rel="canonical" href="' . esc_url( $link ) . '">' . "\n";
}
}
}

View File

@@ -63,6 +63,33 @@ class VC_Settings {
}
}
// Suggested URL slug for the Viator Structure screen: keep an existing
// term's slug so live /tour-destination/{slug}/ links still resolve
// (and 301), otherwise WordPress's own slug for the name.
$existing = array();
if ( $results ) {
$terms = get_terms(
array(
'taxonomy' => 'viator_destination',
'hide_empty' => false,
'meta_query' => array( // phpcs:ignore WordPress.DB.SlowDBQuery
array(
'key' => '_vc_viator_destination_id',
'value' => array_column( $results, 'id' ),
'compare' => 'IN',
),
),
)
);
foreach ( is_wp_error( $terms ) ? array() : $terms as $term ) {
$existing[ (string) get_term_meta( $term->term_id, '_vc_viator_destination_id', true ) ] = $term->slug;
}
}
foreach ( $results as &$result ) {
$result['slug'] = isset( $existing[ $result['id'] ] ) ? $existing[ $result['id'] ] : sanitize_title( $result['name'] );
}
unset( $result );
wp_send_json_success( array( 'results' => $results ) );
}
@@ -345,7 +372,7 @@ class VC_Settings {
<th scope="row"><label for="vc_crawl_destinations"><?php echo esc_html__( 'Destination filter', 'viator-collector' ); ?></label></th>
<td>
<input id="vc_crawl_destinations" type="text" class="large-text" name="vc_settings[crawl_destinations]" value="<?php echo esc_attr( $options['crawl_destinations'] ); ?>" placeholder="<?php echo esc_attr__( 'e.g. 664, 662, 761', 'viator-collector' ); ?>">
<p class="description"><?php echo esc_html__( 'Comma-separated Viator destination IDs to crawl. Leave empty to crawl the whole catalogue. Use the search below to find IDs.', 'viator-collector' ); ?></p>
<p class="description"><?php echo esc_html__( 'Comma-separated Viator destination IDs to crawl. Leave empty to crawl the whole catalogue. Use the search below to find IDs. Used only when no cities are set on the Viator Structure screen.', 'viator-collector' ); ?></p>
<div class="vc-dest-finder" style="margin-top:8px;max-width:640px;">
<input type="search" id="vc-dest-search" class="regular-text" placeholder="<?php echo esc_attr__( 'Search destinations, e.g. Orlando', 'viator-collector' ); ?>">
<button type="button" class="button" id="vc-dest-search-btn"><?php echo esc_html__( 'Search', 'viator-collector' ); ?></button>

View File

@@ -0,0 +1,475 @@
<?php
defined( 'ABSPATH' ) || exit;
/**
* Settings → Viator Structure: the client's region → city tree. Cities can
* only be picked from Viator's destination list, and a save that fails
* VC_Structure::validate() is rejected as a whole (the draft is kept so the
* admin can fix it).
*/
class VC_Structure_Admin {
const PAGE = 'viator-collector-structure';
private static $sync_errors = array();
public static function init() {
add_action( 'admin_menu', array( __CLASS__, 'admin_menu' ) );
add_action( 'admin_post_vc_save_structure', array( __CLASS__, 'handle_save' ) );
add_action( 'admin_enqueue_scripts', array( __CLASS__, 'admin_assets' ) );
add_action( 'admin_notices', array( __CLASS__, 'page_clash_notice' ) );
}
public static function admin_menu() {
add_options_page(
__( 'Viator Structure', 'viator-collector' ),
__( 'Viator Structure', 'viator-collector' ),
'manage_options',
self::PAGE,
array( __CLASS__, 'render_page' )
);
}
public static function admin_assets( $hook ) {
if ( 'settings_page_' . self::PAGE !== $hook ) {
return;
}
wp_enqueue_script( 'vc-structure-admin', VC_PLUGIN_URL . 'assets/js/vc-structure-admin.js', array(), VC_VERSION, true );
wp_localize_script(
'vc-structure-admin',
'vcStructure',
array(
'ajaxUrl' => admin_url( 'admin-ajax.php' ),
'nonce' => wp_create_nonce( 'vc_search_destinations' ),
'i18n' => array(
'searching' => __( 'Searching…', 'viator-collector' ),
'noMatches' => __( 'No matches.', 'viator-collector' ),
'failed' => __( 'Search failed.', 'viator-collector' ),
'add' => __( 'Add', 'viator-collector' ),
'used' => __( 'Already added', 'viator-collector' ),
'confirm' => __( 'Remove this region and all its cities from the structure?', 'viator-collector' ),
'confirmEmpty' => __( 'Save with no regions at all? Every region and city URL will stop working.', 'viator-collector' ),
),
)
);
}
private static function draft_key() {
return 'vc_structure_draft_' . get_current_user_id();
}
public static function render_page() {
if ( ! current_user_can( 'manage_options' ) ) {
return;
}
$draft = get_transient( self::draft_key() );
$errors = array();
$structure = VC_Structure::get();
if ( is_array( $draft ) ) {
delete_transient( self::draft_key() );
$errors = (array) $draft['errors'];
$structure = (array) $draft['structure'];
}
$warnings = get_transient( self::warnings_key() );
$warnings = is_array( $warnings ) ? $warnings : array();
if ( $warnings ) {
delete_transient( self::warnings_key() );
}
$notice = isset( $_GET['vc_notice'] ) ? sanitize_text_field( wp_unslash( $_GET['vc_notice'] ) ) : ''; // phpcs:ignore WordPress.Security.NonceVerification
?>
<div class="wrap">
<h1><?php echo esc_html__( 'Viator Structure', 'viator-collector' ); ?></h1>
<p><?php echo esc_html__( 'Regions appear in the header menu and at /{region}/. Each city is a Viator destination: its tours are imported automatically and listed at /{city}/, with tour pages at /{city}/{tour}/.', 'viator-collector' ); ?></p>
<?php if ( $notice ) : ?>
<div class="notice <?php echo $warnings ? 'notice-warning' : 'notice-success'; ?> is-dismissible"><p><?php echo esc_html( $notice ); ?></p></div>
<?php endif; ?>
<?php if ( $warnings ) : ?>
<div class="notice notice-warning">
<ul style="list-style:disc;margin-left:20px;">
<?php foreach ( $warnings as $warning ) : ?>
<li><?php echo esc_html( $warning ); ?></li>
<?php endforeach; ?>
</ul>
</div>
<?php endif; ?>
<?php if ( $errors ) : ?>
<div class="notice notice-error">
<p><strong><?php echo esc_html__( 'Nothing was saved. Please fix these problems:', 'viator-collector' ); ?></strong></p>
<ul style="list-style:disc;margin-left:20px;">
<?php foreach ( $errors as $error ) : ?>
<li><?php echo esc_html( $error ); ?></li>
<?php endforeach; ?>
</ul>
</div>
<?php endif; ?>
<style>
.vc-region{background:#fff;border:1px solid #c3c4c7;border-radius:6px;padding:12px 16px;margin:0 0 16px;max-width:900px}
.vc-region__head{display:flex;flex-wrap:wrap;gap:8px;align-items:center}
.vc-region__head .vc-tools{margin-left:auto}
.vc-cities{margin:12px 0;width:100%}
.vc-cities td{padding:4px 8px 4px 0;vertical-align:middle}
.vc-city-search{display:flex;flex-wrap:wrap;gap:8px;align-items:center}
.vc-results{width:100%}
.vc-results div{display:flex;gap:8px;align-items:center;padding:2px 0}
.vc-slug-prefix{color:#646970}
</style>
<form method="post" action="<?php echo esc_url( admin_url( 'admin-post.php' ) ); ?>" id="vc-structure-form">
<input type="hidden" name="action" value="vc_save_structure">
<?php wp_nonce_field( 'vc_save_structure' ); ?>
<div id="vc-regions">
<?php
foreach ( $structure as $region ) {
self::render_region( $region );
}
?>
</div>
<p><button type="button" class="button" id="vc-add-region"><?php echo esc_html__( 'Add region', 'viator-collector' ); ?></button></p>
<?php submit_button( __( 'Save structure', 'viator-collector' ) ); ?>
</form>
<template id="vc-tpl-region"><?php self::render_region( array( 'name' => '', 'slug' => '', 'term_id' => 0, 'cities' => array() ) ); ?></template>
<template id="vc-tpl-city"><?php self::render_city( array( 'id' => '', 'name' => '', 'slug' => '' ) ); ?></template>
</div>
<?php
}
/**
* Inputs carry data-f (field) only; the script assigns indexed names on
* submit so reordering never leaves gaps.
*/
private static function render_region( array $region ) {
?>
<div class="vc-region">
<div class="vc-region__head">
<label><?php echo esc_html__( 'Region', 'viator-collector' ); ?>
<input type="text" data-f="name" value="<?php echo esc_attr( $region['name'] ); ?>" required>
</label>
<label><span class="vc-slug-prefix">/</span><input type="text" data-f="slug" value="<?php echo esc_attr( $region['slug'] ); ?>" pattern="[a-z0-9]+(-[a-z0-9]+)*" placeholder="europe">/</label>
<input type="hidden" data-f="term_id" value="<?php echo esc_attr( (string) (int) $region['term_id'] ); ?>">
<span class="vc-tools">
<button type="button" class="button button-small" data-act="up" aria-label="<?php echo esc_attr__( 'Move up', 'viator-collector' ); ?>">↑</button>
<button type="button" class="button button-small" data-act="down" aria-label="<?php echo esc_attr__( 'Move down', 'viator-collector' ); ?>">↓</button>
<button type="button" class="button button-small button-link-delete" data-act="remove-region"><?php echo esc_html__( 'Remove region', 'viator-collector' ); ?></button>
</span>
</div>
<table class="vc-cities"><tbody>
<?php
foreach ( $region['cities'] as $city ) {
self::render_city( $city );
}
?>
</tbody></table>
<div class="vc-city-search">
<input type="search" class="regular-text" placeholder="<?php echo esc_attr__( 'Find a Viator city, e.g. Amsterdam', 'viator-collector' ); ?>">
<button type="button" class="button" data-act="search"><?php echo esc_html__( 'Search', 'viator-collector' ); ?></button>
<div class="vc-results"></div>
</div>
</div>
<?php
}
private static function render_city( array $city ) {
?>
<tr class="vc-city">
<td>
<strong class="vc-city__name"><?php echo esc_html( $city['name'] ); ?></strong>
<span class="description">(ID <span class="vc-city__id"><?php echo esc_html( $city['id'] ); ?></span>)</span>
<input type="hidden" data-f="id" value="<?php echo esc_attr( $city['id'] ); ?>">
<input type="hidden" data-f="name" value="<?php echo esc_attr( $city['name'] ); ?>">
</td>
<td><span class="vc-slug-prefix">/</span><input type="text" data-f="slug" value="<?php echo esc_attr( $city['slug'] ); ?>" pattern="[a-z0-9]+(-[a-z0-9]+)*" required>/</td>
<td>
<button type="button" class="button button-small" data-act="up" aria-label="<?php echo esc_attr__( 'Move up', 'viator-collector' ); ?>">↑</button>
<button type="button" class="button button-small" data-act="down" aria-label="<?php echo esc_attr__( 'Move down', 'viator-collector' ); ?>">↓</button>
<button type="button" class="button button-small button-link-delete" data-act="remove-city"><?php echo esc_html__( 'Remove', 'viator-collector' ); ?></button>
</td>
</tr>
<?php
}
public static function handle_save() {
if ( ! current_user_can( 'manage_options' ) ) {
wp_die( esc_html__( 'You do not have permission to perform this action.', 'viator-collector' ) );
}
check_admin_referer( 'vc_save_structure' );
$raw = isset( $_POST['vc_structure'] ) && is_array( $_POST['vc_structure'] ) ? wp_unslash( $_POST['vc_structure'] ) : array(); // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized -- normalized + validated below.
$structure = VC_Structure::normalize( $raw );
foreach ( $structure as &$region ) {
$region['name'] = sanitize_text_field( $region['name'] );
foreach ( $region['cities'] as &$city ) {
$city['name'] = sanitize_text_field( $city['name'] );
}
unset( $city );
}
unset( $region );
$map = ( new VC_API() )->get_destination_map();
if ( empty( $_POST['vc_structure_present'] ) ) {
$errors = array( __( 'The structure editor did not load correctly, so nothing was saved. Reload the page and try again.', 'viator-collector' ) );
} elseif ( ! $structure && empty( $_POST['vc_confirm_empty'] ) ) {
$errors = array( __( 'Saving an empty structure needs confirmation; nothing was saved.', 'viator-collector' ) );
} elseif ( is_wp_error( $map ) ) {
$errors = array( __( 'Could not load Viator destinations; nothing was saved.', 'viator-collector' ) );
} else {
$errors = VC_Structure::validate( $structure, (array) $map, self::taken_slugs( $structure ) );
// Names always come from Viator, never from the form.
foreach ( $structure as &$region ) {
foreach ( $region['cities'] as &$city ) {
if ( isset( $map[ $city['id'] ] ) ) {
$city['name'] = $map[ $city['id'] ];
}
}
unset( $city );
}
unset( $region );
}
if ( $errors ) {
set_transient(
self::draft_key(),
array(
'errors' => $errors,
// Without the editor's fields there is no draft worth keeping.
'structure' => empty( $_POST['vc_structure_present'] ) ? VC_Structure::get() : $structure,
),
10 * MINUTE_IN_SECONDS
);
self::redirect();
}
self::$sync_errors = array();
$structure = self::sync_terms( VC_Structure::get(), $structure );
update_option( VC_Structure::OPTION, $structure );
VC_Structure::flush_cache();
update_option( 'vc_flush_rewrite', 1 );
VC_Logger::info( sprintf( 'Structure saved: %d regions, %d cities.', count( $structure ), count( VC_Structure::cities( $structure ) ) ) );
if ( self::$sync_errors ) {
set_transient( self::warnings_key(), self::$sync_errors, 10 * MINUTE_IN_SECONDS );
self::redirect( __( 'Structure saved, but some pages could not be set up (see below).', 'viator-collector' ) );
}
self::redirect( __( 'Structure saved.', 'viator-collector' ) );
}
private static function warnings_key() {
return 'vc_structure_warnings_' . get_current_user_id();
}
/**
* Record a term-sync failure: logged, and shown to the admin after save.
*/
private static function sync_error( $message ) {
VC_Logger::error( 'Structure: ' . $message );
self::$sync_errors[] = $message;
}
private static function redirect( $notice = '' ) {
$args = array( 'page' => self::PAGE );
if ( '' !== $notice ) {
$args['vc_notice'] = rawurlencode( $notice );
}
wp_safe_redirect( add_query_arg( $args, admin_url( 'options-general.php' ) ) );
exit;
}
/**
* Slugs (from this structure) already owned by something outside it:
* slug => human label.
*/
public static function taken_slugs( array $structure ) {
global $wpdb;
$slugs = array();
foreach ( $structure as $region ) {
$slugs[] = $region['slug'];
}
$cities = VC_Structure::cities( $structure );
foreach ( $cities as $city ) {
$slugs[] = $city['slug'];
}
$slugs = array_values( array_filter( array_unique( $slugs ) ) );
if ( ! $slugs ) {
return array();
}
$taken = array();
$types = array_diff( get_post_types( array( 'public' => true ) ), array( 'attachment', 'viator_tour' ) );
if ( $types ) {
$slug_in = implode( ',', array_fill( 0, count( $slugs ), '%s' ) );
$type_in = implode( ',', array_fill( 0, count( $types ), '%s' ) );
// phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared,WordPress.DB.DirectDatabaseQuery
$rows = $wpdb->get_results( $wpdb->prepare( "SELECT post_name, post_title, post_type, post_parent FROM {$wpdb->posts} WHERE post_name IN ($slug_in) AND post_type IN ($type_in) AND post_status NOT IN ('trash','auto-draft','inherit')", array_merge( $slugs, array_values( $types ) ) ) );
foreach ( (array) $rows as $row ) {
if ( 'page' === $row->post_type && (int) $row->post_parent ) {
continue; // Child pages live under their parent's path.
}
$label = 'page' === $row->post_type ? 'page "%s"' : 'post "%s"';
$taken[ $row->post_name ] = sprintf( $label, $row->post_title );
}
}
// Destination terms that the structure does not own.
$region_ids = array_filter( array_map( 'intval', array_column( $structure, 'term_id' ) ) );
// A new region (no term yet) adopts an existing term with its slug.
$adoptable = array();
foreach ( $structure as $region ) {
if ( ! (int) $region['term_id'] ) {
$adoptable[] = $region['slug'];
}
}
$terms = get_terms(
array(
'taxonomy' => 'viator_destination',
'slug' => $slugs,
'hide_empty' => false,
)
);
foreach ( is_wp_error( $terms ) ? array() : $terms as $term ) {
if ( in_array( (int) $term->term_id, $region_ids, true ) || in_array( $term->slug, $adoptable, true ) ) {
continue;
}
$viator_id = (string) get_term_meta( $term->term_id, '_vc_viator_destination_id', true );
if ( '' !== $viator_id && isset( $cities[ $viator_id ] ) ) {
continue;
}
$taken[ $term->slug ] = sprintf( 'destination "%s"', $term->name );
}
return $taken;
}
/**
* Mirror the structure into viator_destination terms: regions are
* top-level terms flagged _vc_region, cities are re-parented under them.
* Products are never touched.
*
* @return array $new with every region's term_id filled in.
*/
public static function sync_terms( array $old, array $new ) {
$tax = 'viator_destination';
foreach ( $new as &$region ) {
$term_id = (int) $region['term_id'];
if ( $term_id && ! get_term( $term_id, $tax ) ) {
$term_id = 0;
}
if ( ! $term_id ) {
$existing = get_term_by( 'slug', $region['slug'], $tax );
$term_id = $existing ? (int) $existing->term_id : 0;
}
if ( $term_id ) {
$result = wp_update_term(
$term_id,
$tax,
array(
'name' => $region['name'],
'slug' => $region['slug'],
'parent' => 0,
)
);
} else {
$result = wp_insert_term( $region['name'], $tax, array( 'slug' => $region['slug'] ) );
}
if ( is_wp_error( $result ) ) {
self::sync_error( 'region "' . $region['name'] . '": ' . $result->get_error_message() );
continue;
}
$region['term_id'] = (int) $result['term_id'];
update_term_meta( $region['term_id'], '_vc_region', 1 );
foreach ( $region['cities'] as $city ) {
$city_term = VC_Taxonomies::get_or_create_destination_by_id( $city['id'], $city['name'] );
if ( ! $city_term ) {
self::sync_error( 'could not create the page for city ' . $city['id'] );
continue;
}
$result = wp_update_term(
$city_term,
$tax,
array(
'slug' => $city['slug'],
'parent' => $region['term_id'],
)
);
if ( is_wp_error( $result ) ) {
self::sync_error( 'city "' . $city['name'] . '": ' . $result->get_error_message() );
}
}
}
unset( $region );
// Regions that were removed: delete our own terms; an adopted Viator
// destination term just loses its region flag (it may carry products).
$kept = array_map( 'intval', array_column( $new, 'term_id' ) );
foreach ( $old as $region ) {
$term_id = (int) $region['term_id'];
if ( ! $term_id || in_array( $term_id, $kept, true ) ) {
continue;
}
if ( '' !== (string) get_term_meta( $term_id, '_vc_viator_destination_id', true ) ) {
delete_term_meta( $term_id, '_vc_region' );
} else {
wp_delete_term( $term_id, $tax );
}
}
// Cities that were removed go back to the top level.
$new_cities = VC_Structure::cities( $new );
foreach ( array_keys( VC_Structure::cities( $old ) ) as $id ) {
if ( isset( $new_cities[ (string) $id ] ) ) {
continue;
}
$found = get_terms(
array(
'taxonomy' => $tax,
'hide_empty' => false,
'number' => 1,
'meta_query' => array( // phpcs:ignore WordPress.DB.SlowDBQuery
array(
'key' => '_vc_viator_destination_id',
'value' => (string) $id,
),
),
)
);
if ( ! is_wp_error( $found ) && $found ) {
wp_update_term( $found[0]->term_id, $tax, array( 'parent' => 0 ) );
}
}
return $new;
}
/**
* WordPress does not stop a Page from taking a region/city slug, so warn.
*/
public static function page_clash_notice() {
$screen = function_exists( 'get_current_screen' ) ? get_current_screen() : null;
if ( ! $screen || 'post' !== $screen->base || 'page' !== $screen->post_type ) {
return;
}
$post = get_post();
if ( ! $post || '' === $post->post_name || $post->post_parent ) {
return;
}
$structure = VC_Structure::get();
$owner = '';
foreach ( $structure as $region ) {
if ( $region['slug'] === $post->post_name ) {
$owner = $region['name'];
}
}
foreach ( VC_Structure::cities( $structure ) as $city ) {
if ( $city['slug'] === $post->post_name ) {
$owner = $city['name'];
}
}
if ( '' === $owner ) {
return;
}
echo '<div class="notice notice-warning"><p>' . esc_html( sprintf( __( 'This page\'s URL is also used by the Viator region/city "%s"; the Viator page will take priority.', 'viator-collector' ), $owner ) ) . '</p></div>';
}
}

View File

@@ -0,0 +1,221 @@
<?php
defined( 'ABSPATH' ) || exit;
/**
* The client-managed region → city structure behind the /{region}/,
* /{city}/ and /{city}/{product}/ URLs.
*
* Everything here except get() is plain PHP so it can be unit-tested
* without WordPress (see tests/run.php).
*
* Shape: list of regions, each
* array( 'name', 'slug', 'term_id', 'cities' => list of array( 'id', 'name', 'slug' ) )
* where a city's 'id' is its Viator destination id.
*/
class VC_Structure {
const OPTION = 'vc_structure';
private static $cache = null;
public static function default_regions() {
$regions = array(
'uk' => 'UK',
'europe' => 'Europe',
'asia' => 'Asia',
'middle-east-and-africa' => 'Middle East and Africa',
'americas' => 'Americas',
'australasia' => 'Australasia',
);
$out = array();
foreach ( $regions as $slug => $name ) {
$out[] = array(
'name' => $name,
'slug' => $slug,
'term_id' => 0,
'cities' => array(),
);
}
return $out;
}
public static function get() {
if ( null === self::$cache ) {
$value = get_option( self::OPTION, self::default_regions() );
self::$cache = is_array( $value ) ? $value : self::default_regions();
}
return self::$cache;
}
/**
* Drop the per-request cache (after the option is saved).
*/
public static function flush_cache() {
self::$cache = null;
}
public static function slugify( $s ) {
$s = strtolower( (string) $s );
$s = preg_replace( '/[^a-z0-9]+/', '-', $s );
return trim( $s, '-' );
}
/**
* Shape submitted form data into the structure. Admin-typed slugs are only
* trimmed/lowercased here — validate() rejects anything still invalid
* rather than silently rewriting it.
*/
public static function normalize( array $raw ) {
$out = array();
foreach ( $raw as $region ) {
if ( ! is_array( $region ) ) {
continue;
}
$name = trim( (string) ( $region['name'] ?? '' ) );
$slug = strtolower( trim( (string) ( $region['slug'] ?? '' ) ) );
$cities = array();
foreach ( (array) ( $region['cities'] ?? array() ) as $city ) {
$id = trim( (string) ( is_array( $city ) ? ( $city['id'] ?? '' ) : '' ) );
if ( '' === $id ) {
continue;
}
$city_name = trim( (string) ( $city['name'] ?? '' ) );
$city_slug = strtolower( trim( (string) ( $city['slug'] ?? '' ) ) );
$cities[] = array(
'id' => $id,
'name' => $city_name,
'slug' => '' !== $city_slug ? $city_slug : self::slugify( $city_name ),
);
}
$out[] = array(
'name' => $name,
'slug' => '' !== $slug ? $slug : self::slugify( $name ),
'term_id' => (int) ( $region['term_id'] ?? 0 ),
'cities' => $cities,
);
}
return $out;
}
public static function reserved_slugs() {
return array( 'wp-admin', 'wp-content', 'wp-includes', 'wp-json', 'feed', 'page', 'search', 'tag', 'category', 'author', 'tours', 'tour-destination', 'tour-tag', 'tour-category', 'blog', 'about', 'contact', 'faq', 'embed', 'attachment' );
}
/**
* @param array $destination_map Viator destination id => name.
* @param array $taken slug => label, for slugs owned outside the structure.
* @return string[] Errors; empty when valid.
*/
public static function validate( array $structure, array $destination_map, array $taken ) {
$errors = array();
$slugs = array();
$city_ids = array();
foreach ( $structure as $i => $region ) {
if ( '' === trim( (string) $region['name'] ) ) {
$errors[] = sprintf( 'Region %d has no name.', $i + 1 );
}
$slugs[] = (string) $region['slug'];
foreach ( $region['cities'] as $city ) {
$id = (string) $city['id'];
if ( ! isset( $destination_map[ $id ] ) ) {
$errors[] = sprintf( 'City ID %s is not a Viator destination.', $id );
}
if ( isset( $city_ids[ $id ] ) ) {
$errors[] = sprintf( '%s is listed more than once.', '' !== $city['name'] ? $city['name'] : $id );
}
$city_ids[ $id ] = true;
$slugs[] = (string) $city['slug'];
}
}
$reserved = self::reserved_slugs();
foreach ( array_count_values( $slugs ) as $slug => $count ) {
$slug = (string) $slug;
if ( ! preg_match( '/^[a-z0-9]+(?:-[a-z0-9]+)*$/', $slug ) ) {
$errors[] = sprintf( 'Slug "%s" is invalid: use only a-z, 0-9 and -.', $slug );
continue;
}
if ( in_array( $slug, $reserved, true ) ) {
$errors[] = sprintf( 'Slug "%s" is reserved.', $slug );
}
if ( $count > 1 ) {
$errors[] = sprintf( 'Slug "%s" is used more than once.', $slug );
}
if ( isset( $taken[ $slug ] ) ) {
$errors[] = sprintf( 'Slug "%s" is already used by %s.', $slug, $taken[ $slug ] );
}
}
return array_values( array_unique( $errors ) );
}
/**
* Configured cities in settings order: viator id => city + 'region' slug.
*/
public static function cities( array $structure ) {
$out = array();
foreach ( $structure as $region ) {
foreach ( $region['cities'] as $city ) {
$out[ (string) $city['id'] ] = $city + array( 'region' => $region['slug'] );
}
}
return $out;
}
/**
* The city a product's URL lives under: its Viator primary destination
* when configured, else the first configured city it belongs to, else ''.
*/
public static function canonical_city( array $structure, array $dest_ids, $primary_id ) {
$cities = self::cities( $structure );
if ( '' !== (string) $primary_id && isset( $cities[ (string) $primary_id ] ) ) {
return $cities[ (string) $primary_id ]['slug'];
}
$dest_ids = array_map( 'strval', $dest_ids );
foreach ( $cities as $id => $city ) {
if ( in_array( (string) $id, $dest_ids, true ) ) {
return $city['slug'];
}
}
return '';
}
public static function primary_destination_id( array $destinations ) {
foreach ( $destinations as $destination ) {
if ( is_array( $destination ) && ! empty( $destination['primary'] ) ) {
$ref = $destination['ref'] ?? ( $destination['destinationId'] ?? '' );
return (string) $ref;
}
}
return '';
}
/**
* Explicit per-slug rules (no catch-alls), regions first, then cities.
* Only regions synced to a term (term_id set) are routed, so the unsaved
* presets never claim /europe/ etc. over existing pages. Archives get a
* /page/N/ rule because core's redirect_canonical turns ?paged=N into it.
*/
public static function rewrite_rules( array $structure ) {
$synced = array_values(
array_filter(
$structure,
function ( $region ) {
return (int) $region['term_id'] > 0;
}
)
);
$rules = array();
foreach ( $synced as $region ) {
$rules[ '^' . $region['slug'] . '/page/([0-9]+)/?$' ] = 'index.php?viator_destination=' . $region['slug'] . '&paged=$matches[1]';
$rules[ '^' . $region['slug'] . '/?$' ] = 'index.php?viator_destination=' . $region['slug'];
}
foreach ( self::cities( $synced ) as $city ) {
$rules[ '^' . $city['slug'] . '/page/([0-9]+)/?$' ] = 'index.php?viator_destination=' . $city['slug'] . '&paged=$matches[1]';
$rules[ '^' . $city['slug'] . '/?$' ] = 'index.php?viator_destination=' . $city['slug'];
$rules[ '^' . $city['slug'] . '/([^/]+)/?$' ] = 'index.php?viator_tour=$matches[1]';
}
return $rules;
}
}

View File

@@ -6,10 +6,13 @@
* Filtering stays server-side: every control lives inside #vc-filter-form and
* submits via GET. VC_Display::filter_archive_query() reads the same state.
*
* Args: $vc_title, $vc_subtitle, $vc_query, $vc_form_action.
* Args: $vc_title, $vc_subtitle, $vc_query, $vc_form_action, $vc_after_hero
* (HTML printed between the hero and the results, e.g. the region city grid).
*/
defined( 'ABSPATH' ) || exit;
$vc_after_hero = isset( $vc_after_hero ) ? (string) $vc_after_hero : '';
$f = VC_Display::get_filter_state();
$vc_title = isset( $vc_title ) ? $vc_title : __( 'Explore Tours', 'viator-collector' );
@@ -179,6 +182,8 @@ $vc_hero_img = vc_hero_image_source();
<?php echo vc_ring_badge( 'SCROLL DOWN · SCROLL DOWN · ', '#tour-list', 'scroll' ); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped ?>
</section>
<?php echo $vc_after_hero; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- built by the calling template. ?>
<section class="section" id="tour-list">
<div class="container">
<div class="results">

View File

@@ -0,0 +1,73 @@
<?php
/**
* Region landing page (/{region}/): hero, a grid of the region's cities in
* Viator Structure order, then every tour in those cities — the main query
* on a parent term already includes its child terms.
*/
defined( 'ABSPATH' ) || exit;
get_header();
$vc_term = get_queried_object();
$vc_name = ( $vc_term && ! is_wp_error( $vc_term ) ) ? $vc_term->name : __( 'Tours', 'viator-collector' );
$vc_desc = term_description();
// Child city terms, ordered as on the Viator Structure screen.
$vc_cities = array();
$vc_order = array_keys( VC_Structure::cities( VC_Structure::get() ) );
$vc_terms = get_terms(
array(
'taxonomy' => 'viator_destination',
'parent' => $vc_term ? (int) $vc_term->term_id : 0,
'hide_empty' => false,
)
);
foreach ( is_wp_error( $vc_terms ) ? array() : $vc_terms as $vc_city ) {
$vc_pos = array_search( (string) get_term_meta( $vc_city->term_id, '_vc_viator_destination_id', true ), array_map( 'strval', $vc_order ), true );
$vc_cities[ $vc_pos === false ? PHP_INT_MAX - count( $vc_cities ) : $vc_pos ] = $vc_city;
}
ksort( $vc_cities );
$vc_after_hero = '';
if ( $vc_cities ) {
ob_start();
?>
<section class="vc-section vc-section--destinations">
<div class="vc-container">
<header class="vc-section__head vc-reveal">
<?php /* translators: %s: region name. */ ?>
<h2 class="vc-section__title"><?php echo esc_html( sprintf( __( 'Cities in %s', 'viator-collector' ), $vc_name ) ); ?></h2>
</header>
<div class="vc-destination-grid">
<?php
foreach ( $vc_cities as $vc_city ) {
echo vc_get_template( 'card-destination.php', array( 'term' => $vc_city ) ); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
}
?>
</div>
</div>
</section>
<?php
$vc_after_hero = ob_get_clean();
}
?>
<main class="vc-app vc-listing vc-listing--term vc-listing--region">
<?php
echo vc_get_template( // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
'listing.php',
array(
'vc_title' => $vc_name,
/* translators: %s: region name. */
'vc_subtitle' => $vc_desc ? wp_strip_all_tags( $vc_desc ) : sprintf( __( 'Explore the best tours in %s.', 'viator-collector' ), $vc_name ),
'vc_after_hero' => $vc_after_hero,
'vc_crumb' => array(
array(
'label' => __( 'Tours', 'viator-collector' ),
'url' => get_post_type_archive_link( 'viator_tour' ),
),
),
)
);
?>
</main>
<?php
get_footer();

View File

@@ -0,0 +1,44 @@
<?php
/**
* Minimal test runner for the WordPress-free parts of the plugin.
*
* php tests/run.php
*/
define( 'ABSPATH', __DIR__ . '/' );
require_once dirname( __DIR__ ) . '/includes/class-vc-structure.php';
function vc_assert_same( $expected, $actual, $msg = '' ) {
if ( $expected !== $actual ) {
throw new Exception( $msg . "\n expected: " . var_export( $expected, true ) . "\n actual: " . var_export( $actual, true ) );
}
}
function vc_assert_contains( $needle, array $errors ) {
if ( ! in_array( $needle, $errors, true ) ) {
throw new Exception( 'Missing error: ' . $needle . "\n got: " . var_export( $errors, true ) );
}
}
foreach ( glob( __DIR__ . '/test-*.php' ) as $file ) {
require_once $file;
}
$passed = 0;
$failed = 0;
foreach ( get_defined_functions()['user'] as $fn ) {
if ( 0 !== strpos( $fn, 'test_' ) ) {
continue;
}
try {
$fn();
$passed++;
} catch ( Throwable $e ) {
$failed++;
echo 'FAIL ' . $fn . ': ' . $e->getMessage() . "\n";
}
}
echo $passed . ' passed, ' . $failed . " failed\n";
exit( $failed ? 1 : 0 );

View File

@@ -0,0 +1,173 @@
<?php
/**
* VC_Structure unit tests.
*/
function vc_fixture_structure() {
return array(
array(
'name' => 'Europe',
'slug' => 'europe',
'term_id' => 0,
'cities' => array(
array( 'id' => '737', 'name' => 'Amsterdam', 'slug' => 'amsterdam' ),
array( 'id' => '479', 'name' => 'Paris', 'slug' => 'paris' ),
),
),
array(
'name' => 'Americas',
'slug' => 'americas',
'term_id' => 0,
'cities' => array(
array( 'id' => '678', 'name' => 'Boston', 'slug' => 'boston' ),
),
),
);
}
function vc_fixture_map() {
return array( '737' => 'Amsterdam', '479' => 'Paris', '678' => 'Boston', '22' => 'Victoria' );
}
function test_default_regions() {
$regions = VC_Structure::default_regions();
vc_assert_same(
array( 'uk', 'europe', 'asia', 'middle-east-and-africa', 'americas', 'australasia' ),
array_column( $regions, 'slug' )
);
vc_assert_same( 'Middle East and Africa', $regions[3]['name'] );
vc_assert_same( array(), $regions[0]['cities'] );
vc_assert_same( 0, $regions[0]['term_id'] );
}
function test_normalize_fills_slugs() {
$s = VC_Structure::normalize(
array(
array(
'name' => ' Middle East and Africa ',
'slug' => '',
'term_id' => '7',
'cities' => array(
array( 'id' => '', 'name' => 'Ghost', 'slug' => 'ghost' ),
array( 'id' => '828', 'name' => 'Dubai', 'slug' => '' ),
),
),
)
);
vc_assert_same( 'Middle East and Africa', $s[0]['name'] );
vc_assert_same( 'middle-east-and-africa', $s[0]['slug'] );
vc_assert_same( 7, $s[0]['term_id'] );
vc_assert_same( array( array( 'id' => '828', 'name' => 'Dubai', 'slug' => 'dubai' ) ), $s[0]['cities'] );
}
function test_validate_ok() {
vc_assert_same( array(), VC_Structure::validate( vc_fixture_structure(), vc_fixture_map(), array() ) );
}
function test_validate_unknown_city() {
$s = vc_fixture_structure();
$s[1]['cities'][0]['id'] = '999';
vc_assert_contains( 'City ID 999 is not a Viator destination.', VC_Structure::validate( $s, vc_fixture_map(), array() ) );
}
function test_validate_duplicate_city() {
$s = vc_fixture_structure();
$s[1]['cities'][] = array( 'id' => '737', 'name' => 'Amsterdam', 'slug' => 'amsterdam-2' );
vc_assert_contains( 'Amsterdam is listed more than once.', VC_Structure::validate( $s, vc_fixture_map(), array() ) );
}
function test_validate_duplicate_slug() {
$s = vc_fixture_structure();
$s[1]['slug'] = 'paris';
vc_assert_contains( 'Slug "paris" is used more than once.', VC_Structure::validate( $s, vc_fixture_map(), array() ) );
}
function test_validate_bad_slug() {
$s = vc_fixture_structure();
$s[0]['cities'][0]['slug'] = 'amsterdam!';
$s[1]['cities'][0]['slug'] = 'New York';
$errors = VC_Structure::validate( $s, vc_fixture_map(), array() );
vc_assert_contains( 'Slug "amsterdam!" is invalid: use only a-z, 0-9 and -.', $errors );
vc_assert_contains( 'Slug "New York" is invalid: use only a-z, 0-9 and -.', $errors );
}
function test_validate_reserved() {
$s = vc_fixture_structure();
$s[0]['cities'][0]['slug'] = 'contact';
vc_assert_contains( 'Slug "contact" is reserved.', VC_Structure::validate( $s, vc_fixture_map(), array() ) );
}
function test_validate_taken_slug() {
$s = vc_fixture_structure();
$s[1]['cities'][] = array( 'id' => '22', 'name' => 'Victoria', 'slug' => 'victoria' );
$errors = VC_Structure::validate( $s, vc_fixture_map(), array( 'victoria' => 'destination "Victoria"' ) );
vc_assert_contains( 'Slug "victoria" is already used by destination "Victoria".', $errors );
}
function test_validate_empty_region() {
$s = vc_fixture_structure();
$s[0]['name'] = '';
vc_assert_contains( 'Region 1 has no name.', VC_Structure::validate( $s, vc_fixture_map(), array() ) );
}
function test_canonical_city_primary() {
vc_assert_same( 'paris', VC_Structure::canonical_city( vc_fixture_structure(), array( '479', '737' ), '479' ) );
}
function test_canonical_city_fallback_order() {
vc_assert_same( 'amsterdam', VC_Structure::canonical_city( vc_fixture_structure(), array( '678', '479', '737' ), '5555' ) );
}
function test_canonical_city_none() {
vc_assert_same( '', VC_Structure::canonical_city( vc_fixture_structure(), array( '5555' ), '' ) );
}
function test_primary_destination_id() {
vc_assert_same( '2', VC_Structure::primary_destination_id( array( array( 'ref' => '1' ), array( 'ref' => '2', 'primary' => true ) ) ) );
vc_assert_same( '', VC_Structure::primary_destination_id( array() ) );
}
function vc_fixture_synced() {
$s = vc_fixture_structure();
$s[0]['term_id'] = 11;
$s[1]['term_id'] = 12;
return $s;
}
function test_rewrite_rules() {
vc_assert_same(
array(
'^europe/page/([0-9]+)/?$' => 'index.php?viator_destination=europe&paged=$matches[1]',
'^europe/?$' => 'index.php?viator_destination=europe',
'^americas/page/([0-9]+)/?$' => 'index.php?viator_destination=americas&paged=$matches[1]',
'^americas/?$' => 'index.php?viator_destination=americas',
'^amsterdam/page/([0-9]+)/?$' => 'index.php?viator_destination=amsterdam&paged=$matches[1]',
'^amsterdam/?$' => 'index.php?viator_destination=amsterdam',
'^amsterdam/([^/]+)/?$' => 'index.php?viator_tour=$matches[1]',
'^paris/page/([0-9]+)/?$' => 'index.php?viator_destination=paris&paged=$matches[1]',
'^paris/?$' => 'index.php?viator_destination=paris',
'^paris/([^/]+)/?$' => 'index.php?viator_tour=$matches[1]',
'^boston/page/([0-9]+)/?$' => 'index.php?viator_destination=boston&paged=$matches[1]',
'^boston/?$' => 'index.php?viator_destination=boston',
'^boston/([^/]+)/?$' => 'index.php?viator_tour=$matches[1]',
),
VC_Structure::rewrite_rules( vc_fixture_synced() )
);
}
function test_rewrite_rules_empty_region() {
$rules = VC_Structure::rewrite_rules( array( array( 'name' => 'Europe', 'slug' => 'europe', 'term_id' => 11, 'cities' => array() ) ) );
vc_assert_same(
array(
'^europe/page/([0-9]+)/?$' => 'index.php?viator_destination=europe&paged=$matches[1]',
'^europe/?$' => 'index.php?viator_destination=europe',
),
$rules
);
}
// Before the structure is ever saved, get() returns the unsynced presets:
// they must not claim /uk/, /europe/, … over existing pages.
function test_rewrite_rules_skip_unsynced_regions() {
vc_assert_same( array(), VC_Structure::rewrite_rules( VC_Structure::default_regions() ) );
}

View File

@@ -4,13 +4,13 @@ defined('ABSPATH') || exit;
/**
* Plugin Name: Viator Collector
* Description: Import Viator tours using the Viator Partner API and display them with native WordPress post types, templates, and shortcodes.
* Version: 1.8.15
* Version: 1.9.0
* Author: Amir Bagheri
* License: GPL-2.0-or-later
* Text Domain: viator-collector
*/
define('VC_VERSION', '1.8.15');
define('VC_VERSION', '1.9.0');
define('VC_PLUGIN_FILE', __FILE__);
define('VC_PLUGIN_DIR', plugin_dir_path(__FILE__));
define('VC_PLUGIN_URL', plugin_dir_url(__FILE__));