How to add "blog" slug to wordpress posts?

php, wordpress

Solution

just go to your permalink settings make sure you have it set to custom and add "/blog/" in front of %post_name% this way you'll have "/blog/" in front of your structure, if you also use CPT make sure that you add 'with_front'=>false when you register them like this:

'rewrite' => array( 'slug' => 'cpt_name', 'with_front'=> false ),

the way it works is: if your permalink structure is /blog/, then your links will be: if with_front = false permalink: /news/ if with_front = true permalink: /blog/news/

and the issue is that it defaults to true

the wordpress codex page that has this info is here

what you also have to note is: If registering a post type inside of a plugin, call flush_rewrite_rules() in your activation and deactivation hook (see Flushing Rewrite on Activation below). If flush_rewrite_rules() is not used, then you will have to manually go to Settings > Permalinks and refresh your permalink structure before your custom post type will show the correct structure.

Problem

i am working on wordpress project that i have one diffuculty, i want to add "Blog" slug to blog posts for example my current blog slug is like ``` http://www.abc.com/post ``` i want to make it like ``` http://www.abc.com/blog/post ``` i don't want to create custom post type i need to use existing ones i have tried many solution such as changing permalinks to blog/%postname% one solution worked for me below is my code ``` add_action( 'init', 'my_new_default_post_type', 1 ); function my_new_default_post_type() { register_post_type( 'post', array( 'labels' => array( 'name_admin_bar' => _x( 'Post', 'add new on admin bar' ), ), 'public' => true, '_builtin' => false, '_edit_link' => 'post.php?post=%d', 'capability_type' => 'post', 'map_meta_cap' => true, 'hierarchical' => false, 'rewrite' => array( 'slug' => 'blog' ), 'query_var' => false, 'with_front' => false, 'supports' => array( 'title', 'editor', 'author', 'thumbnail', 'excerpt', 'trackbacks', 'custom-fields', 'comments', 'revisions', 'post-formats' ), ) ); } ``` i have added this code to my functions.php and added slug to posts. but problem came when i clicked on particular post it will redirected to 404 page. and if i remove this code it i will redirecting to correct post. need your suggesions.

Original source