Why your custom post type URLs 404 (and how to never re-save permalinks again)
Описание и применение
Решение автоматизирует обновление правил перезаписи в WordPress только при изменении маршрутов, устраняя необходимость вручную сохранять постоянные ссылки и предотвращая проблемы с производительностью.
Задача
Custom post type URLs return 404 until permalinks are re‑saved, causing a recurring manual ritual.
Результат
The recipe automates rewrite rule flushing only when routes change, eliminating the need to manually re‑save permalinks and preventing performance regressions.
Рабочий процесс
- Register the custom post type during init.
- Hook a function to wp_loaded that checks a fingerprint of $wp_rewrite.
- If the fingerprint differs from the stored option, perform a soft flush_rewrite_rules(false) and update the fingerprint option.
- Optionally cap rebuilds to 5 per 10 minutes to avoid excessive flushing on admin‑ajax requests.
- Ensure the hook runs at priority PHP_INT_MAX so all routes are registered.
- Use a soft flush to avoid rewriting .htaccess.
- Maintain a counter of rebuilds in an option to enforce the cap.
Доказательства
WordPress doesn’t create any URL rules yet. It records a permastruct (/recipes/%recipe%) in the global $wp_rewrite object.
The function’s documentation warns that flushing is expensive and belongs in activation hooks, not on every page load.
A soft flush rebuilds the rules in the database and leaves .htaccess alone.
I wrote a test that reproduced it first: alternate 10 front‑end requests with 10 admin‑ajax.php requests and count the rebuilds. The result was 20 rebuilds in 20 requests.
- Дата записи: 2026-10-15T14:40:58.955Z