I want to make my WordPress blog URLs more flexible. Right now, my permalink structure is %post_id%/%postname%
. But I’d like WordPress to only use the post ID when finding the right post. This way, I could change the post title without breaking links.
For example, these URLs should all go to the same post (ID 345):
myblog.com/345/original-post-name
myblog.com/345/different-name
myblog.com/345
I’ve tried messing with my .htaccess file, but no luck. Here’s what I’ve got:
RewriteEngine on
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
I also tried adding this rule, but it didn’t work:
RewriteRule ^([0-9]+)/?([a-zA-Z0-9\-]+)/?$ index.php?p=$1 [QSA]
Any ideas on how to make this work? I’m stumped!
As someone who’s worked extensively with WordPress, I can offer a solution that doesn’t require modifying your theme files or .htaccess. Instead, you can use a plugin called ‘Custom Permalinks’ to achieve what you’re after.
Install and activate the plugin, then go to each post and set a custom permalink structure like ‘/345/%postname%’. This way, WordPress will recognize the post by its ID, regardless of what comes after.
For even more flexibility, you could create a small custom plugin that hooks into ‘pre_get_posts’ and modifies the query based on the URL structure. This approach gives you full control over URL handling without touching core files.
Remember to thoroughly test any changes to ensure they don’t break existing functionality or SEO. Good luck with your customization!
I’ve actually implemented something similar on my own WordPress site, and I can tell you it’s definitely possible. The key is to modify your theme’s functions.php file rather than messing with .htaccess.\n\nHere’s what worked for me:\n\nAdd this to your functions.php:\n\nphp\nfunction custom_post_parse_request($query) {\n if (!$query->is_main_query() || 2 != count($query->query) || !isset($query->query['page'])) {\n return;\n }\n if (preg_match('/^[0-9]+$/', $query->query['page'])) {\n $query->set('p', $query->query['page']);\n $query->set('page', '');\n }\n}\nadd_action('parse_request', 'custom_post_parse_request');\n
\n\nThis function intercepts WordPress’s request parsing and checks if the URL contains just a number. If it does, it sets that number as the post ID.\n\nYou’ll also need to update your permalink structure in the WordPress admin to just /%post_id%/.\n\nAfter implementing this, all your desired URL formats should work as expected. Just remember to flush your permalinks after making these changes!
hey there! i’ve dealt with this before. you could try using the ‘wp_rewrite’ filter. add this to your functions.php:
add_filter(‘wp_rewrite’, ‘custom_rewrite_rules’);
function custom_rewrite_rules($wp_rewrite) {
$wp_rewrite->add_rule(‘^([0-9]+)/?’, ‘index.php?p=$matches[1]’, ‘top’);
}
don’t forget to flush your permalinks after. this should work for ya!