Adding "/blog/" Prefix to Default WordPress Posts

When managing a WordPress site, you might want to add a /blog/ prefix exclusively to default posts while leaving pages and custom post types unaffected. This ensures a clear content hierarchy and better URL structure for your blog. Below is a guide to achieving this with custom code.

Step 1: Add /blog/ to Post Permalinks

To prepend /blog/ to the URL structure of WordPress posts, use the post_link filter. This allows the modification of permalinks specifically for posts.

  
// Add '/blog/' prefix to default WordPress posts' permalinks
function add_blog_to_post_permalink($permalink, $post, $leavename) {
    if (is_object($post) && $post->post_type === 'post') {
        // Add '/blog/' to the permalink for posts
        $permalink = str_replace(home_url(), home_url('/blog'), $permalink);
    }
    return $permalink;
}
add_filter('post_link', 'add_blog_to_post_permalink', 10, 3);

Step 2: Redirect Old URLs Without /blog/

To prevent broken links and maintain SEO consistency, implement a redirect for old post URLs that do not include the /blog/ prefix. Use the template_redirect hook for this purpose.

  
// Redirect old post URLs without '/blog/' to the new URLs
function redirect_post_without_blog_slug() {
    // Check if we are on a single post (and not a page or custom post type)
    if (is_single() && get_post_type() === 'post') {
        // Get the current URL
        $current_url = home_url($_SERVER['REQUEST_URI']);
        
        // Check if the URL already contains '/blog/'
        if (strpos($current_url, '/blog/') === false) {
            // Get the post slug
            $post_slug = get_post_field('post_name', get_queried_object_id());
            // Construct the new URL with '/blog/' prefix
            $new_url = home_url('/blog/' . $post_slug . '/');
            
            // Redirect to the new URL with a 301 status (permanent redirect)
            wp_redirect($new_url, 301);
            exit;
        }
    }
}
add_action('template_redirect', 'redirect_post_without_blog_slug');

Step 3: Flush Rewrite Rules

After adding the above code, flush WordPress rewrite rules to apply the changes:

  1. Go to Settings > Permalinks in the WordPress admin dashboard.
  2. Click Save Changes (no need to modify any settings).

No comments:

Post a Comment