Prefix WordPress Post Permalink
Adding an action to generate_rewrite_rules gives you the ability to add your custom blog rule into the list of rules, We insert it at the top of the list allowing it to get priority over rules further down.
You can now access your posts via the new structure of url /blog/your-post-slug, Make sure your refresh your permalinks by going to settings > permalinks.
All that is left to do is change the output of wordpress’s the_permalink() and get_permalink() functions, by hooking into the post_link and changing the output of links for the post post_type.
function add_rewrite_rules( $wp_rewrite )
{
$new_rules = array(
'blog/page/(.+?)/?$' => 'index.php?post_type=post&paged='. $wp_rewrite->preg_index(1),
'blog/(.+?)/?$' => 'index.php?post_type=post&name='. $wp_rewrite->preg_index(1),
);
$wp_rewrite->rules = $new_rules + $wp_rewrite->rules;
}
add_action('generate_rewrite_rules', 'add_rewrite_rules');
function change_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', 'change_blog_links', 1, 3);
Leave a Reply
Fields marked with an * are required to post a comment