WordPress中修改固定链接内的post_id(不改动实际文章ID)
Absolutely doable! You won’t have to mess with the actual post IDs stored in your database—we can tweak the permalink output and handle incoming requests using WordPress’s built-in hooks. Here’s a step-by-step breakdown:
1. 修改前端输出的固定链接(让URL里的ID+1)
We’ll use the post_link filter to adjust the permalink right before it’s rendered on your site. Add this code to your active theme’s functions.php file, or create a simple custom plugin for it (recommended to avoid losing changes when updating themes):
add_filter('post_link', 'adjust_permalink_post_id', 10, 3); function adjust_permalink_post_id($permalink, $post, $leavename) { // Only target single post permalinks if (is_single($post->ID) && $post->post_type === 'post') { // Extract the post ID from the original permalink $original_id = $post->ID; $new_id = $original_id + 1; // Replace the original ID in the permalink with the new one $permalink = str_replace('/' . $original_id . '/', '/' . $new_id . '/', $permalink); } return $permalink; }
2. 处理反向请求(让修改后的URL能正确指向原文章)
Now we need to tell WordPress how to map the modified ID back to the actual post ID when someone visits the adjusted URL. Use the request filter for this:
add_filter('request', 'map_adjusted_id_to_original'); function map_adjusted_id_to_original($query_vars) { // Check if we're dealing with a post ID in the request if (isset($query_vars['p'])) { // Subtract 1 from the requested ID to get the original post ID $query_vars['p'] = intval($query_vars['p']) - 1; } return $query_vars; }
3. 最后一步:刷新固定链接规则
After adding the code, go to Settings → Permalinks in your WordPress admin. You don’t need to change the structure—just click the "Save Changes" button. This flushes the rewrite rules so WordPress picks up our new permalink logic.
额外注意事项
- If you’re using custom post types, modify the
$post->post_type === 'post'check to include your CPT slug (e.g.,'product'). - Test thoroughly: Check existing post links to confirm they show the +1 ID, then visit the modified URL to make sure it loads the correct post.
- Using a custom plugin instead of
functions.phpis safer—if something breaks, you can just deactivate the plugin without messing up your theme.
内容的提问来源于stack exchange,提问作者Mr. Jo

