We can add url prefix for wordpress blog posts in two way.
- Using permalink structure settings
- Using hooks
1. Using permalink structure settings
You can add blog post suffix easily by updating permalink structure to
/blog/%post_name%/ , here we are using blog text as suffix for all post url.
After saving the settings, post url will be look like this :
yourdomain.com/blog/post-name
But drawback of this is way is that it will apply for all blog post and custom post type as well. so if you are using custom post type in your wordpress site then you will need to avoid this option and choose the second option.
2. Using Hooks
Using hooks function wordpress has allow you to add the suffix url for every post type separately. In this way suffix url will apply only for a particular post type. Please follow below steps to add suffix url using hooks function
a) Add this rewrite at the end of you function.php
function wpexpertsin_add_rewrite_rules( $wp_rewrite ) {
$new_rules = array(
'^blog/(?!.*page)([0-9-a-z-_]+)/?' => 'index.php?post_type=post&name='. $wp_rewrite->preg_index(1),
);
$wp_rewrite->rules = $new_rules + $wp_rewrite->rules;
}
add_action('generate_rewrite_rules', 'wpexpertsin_add_rewrite_rules');
function wpexpertsin_blog_links($post_link, $id=0){
$post = get_post($id);
if( is_object($post) && $post->post_type == 'post'){
return home_url('/blog/'. $post->post_name.'/');
}
return $post_link;
}
add_filter('post_link', 'wpexpertsin_blog_links', 1, 3);
b) Go to Settings > Permalinks and click Save Changes