This tutorial will show you how to force rewrite WordPress URLs to use /blog/ in posts permalink structure. Websites that have a large number of pages, custom post types, posts, and posts categories may benefit by using the prefix “blog” in the URL instead of the blog category name slug. Most importantly, blogs that have posts in multiple categories, or categories that get removed or changed, should use this kind of URL structure.
For example, if a website’s blog has URLs that look like the following:
The category slug name is replaced with “blog” and the URLs are rewritten to look like the following:
Posts Permalink Structure for SEO
It is recommended by Yoast SEO to use the category and the post name slug in the URL for the perfect WordPress SEO permalink structure. This can be accomplished by editing the permalinks in the WordPress admin area. There are a number of tags available to use. For the sake of this tutorial, use the following format:
To start, go to the Permalinks Settings page in the WordPress admin:
Settings > Permalinks
Next, add the tags into the custom structure field:
The above settings will output the category name and the post name in the permalink. The URLs will look like the following:
WordPress does not offer a simple mechanism or option to rewrite only the posts permalink structure. Editing the above Custom Structure field to force “/blog/%postname%” is an incomplete solution.
Replace Category Names with /blog/ in Posts Permalink Structure
The first part of the solution to adding the /blog/ prefix to the post URLs is to use the post_link WordPress filter to only modify the posts. The next step is to rewrite the URLs that include “blog/” by hooking into the generate_rewrite_rules WordPress function. The category name will be stripped from the posts permalink structure and be replaced with “blog”. Each posts attachment, embed, trackback, feed, page, and comments URL will also be rewritten to correctly resolve to the new post URL.
Your website’s paginated pages may not display correctly when creating a page with “blog” as the slug and using pagination. However, the first rewrite rule below solves this issue so that WordPress finds the next page before trying to find the single post.
Paste the following code snippet into the functions.php file of your active parent theme or child theme.
Use the Rewrite Rules Inspector plugin to check that WordPress is correctly using the updated rewrite rules.
Make sure to flush your rewrite rules after inserting the above code snippet in the functions.php file. Save the permalinks a couple of times in the WordPress admin area:
Settings > Permalinks
Need help? Our WordPress Development Service is a comprehensive solution for small, medium and enterprise-level businesses. Call us at 602-633-4758 for a free consultation.