WordPress插件需求:实现无重定向的目录式URL参数结构
Got it, let's tackle this problem step by step. You want to turn those query-string-heavy URLs like domainname.com/test?book_id=BWBR0002656&art_id=1 into clean, directory-style paths like domainname.com/test/BWBR0002656/1—and you need this to happen without redirects, right?
This requires two key parts: frontend JavaScript to update the URL without reloading and WordPress backend rewrite rules to map the new URL structure back to your plugin's query parameters (otherwise you'll get 404 errors).
1. Frontend JavaScript: Update URL to Directory Structure
First, we'll write JS that checks for existing query parameters, converts them to the directory format, and updates the browser's URL using history.pushState (which avoids a page reload).
Add this script to your plugin's frontend code (either enqueue it or include it in your template):
document.addEventListener('DOMContentLoaded', function() { // Get current URL and its search parameters const url = new URL(window.location.href); const bookId = url.searchParams.get('book_id'); const artId = url.searchParams.get('art_id'); // Only update if both parameters exist if (bookId && artId) { // Build the new directory-style path const newPath = `${url.pathname}/${bookId}/${artId}`; // Update the URL without reloading the page history.pushState({}, '', newPath); } });
Bonus: Handle Link Clicks (If Needed)
If you have links that generate the query parameter URLs, you'll want to intercept those clicks and rewrite the URL on the fly:
document.addEventListener('click', function(e) { const link = e.target.closest('a'); if (!link) return; const url = new URL(link.href); const bookId = url.searchParams.get('book_id'); const artId = url.searchParams.get('art_id'); if (bookId && artId) { e.preventDefault(); const newPath = `${url.pathname}/${bookId}/${artId}`; history.pushState({}, '', newPath); // Optional: Trigger your plugin's content load logic here instead of reloading loadBookContent(bookId, artId); } });
Replace loadBookContent with whatever function your plugin uses to fetch and display the text based on book_id and art_id.
2. WordPress Backend: Add Rewrite Rules
The frontend URL looks clean now, but WordPress doesn't know what to do with domainname.com/test/BWBR0002656/1—it'll throw a 404 unless we tell it to map this path to the original query parameters.
Add this code to your plugin's main file (or your theme's functions.php):
// Add custom rewrite rule function custom_book_rewrite_rule() { add_rewrite_rule( '^test/([^/]+)/([^/]+)/?$', // Match the directory path 'index.php?pagename=test&book_id=$matches[1]&art_id=$matches[2]', // Map to query params 'top' ); } add_action('init', 'custom_book_rewrite_rule'); // Register query variables so WordPress recognizes them function custom_book_query_vars($vars) { $vars[] = 'book_id'; $vars[] = 'art_id'; return $vars; } add_filter('query_vars', 'custom_book_query_vars');
Important Final Step: Flush Rewrite Rules
After adding this code, you need to flush WordPress's rewrite rules to make the new rule active:
- Go to Settings > Permalinks in your WordPress admin
- Don't change anything—just click the Save Changes button. This will flush the rules.
Testing It Out
- Visit your original URL:
domainname.com/test?book_id=BWBR0002656&art_id=1 - The JS should automatically update the URL to
domainname.com/test/BWBR0002656/1without reloading - The page should still load the correct content (thanks to the backend rewrite rule mapping the path back to the query params)
内容的提问来源于stack exchange,提问作者Jeroen_13

