How to add slug for default posts

Let’s imagine, that your customer or you use default posts for the blog. How you known in this case, URL of posts don’t contains any slug. But your customer or you need add some slug to URL, for example, for improve SEO performance of a site. And if we say about custom post type then it’s all clear, we just using argument ‘slug’. But what about default post type post?

Change default posts slug

Problem: Change default posts slug, for example to 'blog'.

Solution: We have at least 2 ways for resolve this problem.

First way. Go to admin dashboard, SettingsPermalinks Custom structure and put next string /blog/%postname%/ and save changes. But here's the thing, if we have any custom post types (or if we'll have custom post types in future) we'll can get our slug 'blog' for their URL. Therefore we should be check it and if really that, are need add/change to function register_post_type() for all custom post types key FALSE for 'with_front' for 'rewrite' argument.

...
'rewrite' => [
    //'slug' => 'resource', // slug CPT
    'with_front' => false, // don't use generally prefix from Settings
],
...

In addition, 'blog' slug will be added to categories and tags. In order remove it from those URLs we should be again go to Settings → Permalinks → Optional section and add:
Category base - category/.
Tag base - tag/.

Second way. In the functions.php we should be next code:

<?php
// Change Default Posts Slug
add_filter( 'register_post_type_args', 'new_register_post_type_args', 10, 2 );

function new_register_post_type_args( $args, $post_type ) {
	if ( $post_type !== 'post' ) {
		return $args;
	}

	$args['rewrite'] = [
		'slug' => 'blog',
		'with_front' => true,
	];
	
	return $args;
}

This way URL like https://site_name.com/blog/post-title/ are work, but generated links in are wrong now.

Links can be fixed by forcing custom permalink structure for the building posts.

<?php
add_filter( 'pre_post_link', 'new_post_link', 10, 2 );

function new_post_link( $permalink, $post ) {
	if ( $post->post_type !== 'post' ) {
		return $permalink;
	}
	
	return '/blog/%postname%/';
}

Disadvantage for this way, that post will be available for two URLs that contain /blog/ and without it.

NOTE: Remember about on the need redirects for all posts! As an option we can use plugin Yoast SEO. This plugin allows you get list all post by address https://your-site-name.com/post-sitemap.xml After then we can create document and add here all old and new links, save as redirects.csv and bulk import by use plugin Redirection by John Godley.

Sources:

  1. https://wordpress.stackexchange.com/questions/131666/possible-to-change-the-slug-of-default-post-type/131676
  2. https://stackoverflow.com/questions/52427918/how-to-change-wordpress-default-posts-permalinks-programmaticall

Leave Comment

One Reply to “Change default posts slug”

Your email address will not be published. Required fields are marked *