Frnnd Sgz
Frnnd Sgz

Reputation: 328

Remove parts of the url for a wordpress site

I'm triyng to put a server rule on a htaccess to remove some parts of the urls that wordpress generates via permalinks when you work with CPT (custom post types). The fact is that I'm not sure that this can work via a simple Rewrite rule.

my urls actually looks like this:

http://www.13mdn.com/newreleases_post/white-stripes.

I would like to change to:

http://www.13mdn.com/white-stripes

and

http://www.13mdn.com/oldreleases_post/the-who

I would like to change to:

http://www.13mdn.com/the-who

here is the rules I made on htacces file

RewriteRule ^newreleases_post/(.*)$ $1
RewriteRule ^oldreleases_post/(.*)$ $1

This don't work.

I also Have tried puting the rule via wordpress function like this

Upvotes: 0

Views: 1654

Answers (2)

vard
vard

Reputation: 4156

To remove custom post type slug from post URLs, you need to add the following in your functions.php:

function remove_cpt_slug($post_link, $post, $leavename) {
    if($post->post_type == 'newreleases_post' || $post->post_type == 'oldreleases_post') {
        $post_link = str_replace('/'.$post->post_type.'/', '/', $post_link);
    }
    return $post_link;
}
add_filter('post_type_link', 'remove_cpt_slug', 10, 3);

This will change all the URL for your CPTs to remove the CPT name. To let Wordpress know that he should check for those CPT, add the following function:

function request_cpt($query) {
    if(! $query->is_main_query()) {
        return;
    }
    if(count($query->query) != 2 || ! isset( $query->query['page'])) {
        return;
    }
    if (! empty( $query->query['name'])) {
        $query->set('post_type', array('post', 'newreleases_post', 'oldreleases_post'));
    }
}
add_action('pre_get_posts', 'request_cpt');

Last step, to redirect your old URLs to the new one, add this on the top of your htaccess (before the Wordpress part):

RewriteEngine On
RewriteRule ^newreleases_post/(.*)$ $1 [L,R=301]
RewriteRule ^oldreleases_post/(.*)$ $1 [L,R=301]

Please note that this could end up to conflicts if you use the same permalink for a CPT and a page.

Upvotes: 4

ehmad11
ehmad11

Reputation: 1395

Simply change your permalink to a custom format : /%postname%/

Upvotes: 0

Related Questions