Many times, you would like to remove the custom post type slug from urls. You don’t want frontend users to see you custom post type slug and to know you are using one. I kept looking for solutions, modified rewrite rules and did lots of things finally found a very easier solution. This solution works for hierarchical posts and non-hierarchical both. It also removes parent slug from hierarchical posts.  I hope this would help you guys. Here is the code.

add_filter(
'post_type_link',
'custom_post_type_link',
10,
3
);

function custom_post_type_link($permalink, $post, $leavename) {
if (!gettype($post) == 'post') {
return $permalink;
}
switch ($post->post_type) {
case 'your_custompost_type_slug':
$permalink = get_home_url() . '/' . $post->post_name . '/';
break;
}

return $permalink;
}

The above code snippet will be put into your functions.php and it will remove slugs from all post urls. So where ever in the template you are displaying the_permalink() . But clicking those links you will get a 404, page not found if you don’t set the right query vars which are set in code given below:

add_action(
'pre_get_posts',
'custom_pre_get_posts'
);

function custom_pre_get_posts($query) {
global $wpdb;

if(!$query->is_main_query()) {
return;
}

$post_name = $query->get('name');

$post_type = $wpdb->get_var(
$wpdb->prepare(
'SELECT post_type FROM ' . $wpdb->posts . ' WHERE post_name = %s LIMIT 1',
$post_name
)
);

switch($post_type) {
case 'your_custompost_type_slug':
$query->set('your_custompost_type_slug', $post_name);
$query->set('post_type', $post_type);
$query->is_single = true;
$query->is_page = false;
break;
}

return $query;
}

So adding the above two snippets to funtions.php will remove custom post type slugs from urls. But last thing is:

don’t forget to replace your_custompost_type_slug in above code with your custom post type slug.  Happy coding!

courtesy:<a href=”http://ryansechrest.com/2013/04/remove-post-type-slug-in-custom-post-type-url-and-move-subpages-to-website-root-in-wordpress/”>Ryan Sechrest. </a>

Yumna Tatheer

I am a Computer Science graduate and a part time blogger from Lahore, Pakistan. I am a PHP programmer and a wordpress expert.

More Posts

Follow Me:
Facebook