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