phpwordpressurlcategoriesslug

Problem removing sub category from permalink URL of blog post in Wordpress


I'm using this solution to remove sub-categories from the url on my blog posts: Remove sub category slug from permalink URL of blog post and custom post type in WordPress

add_filter('post_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 'post':
    //$permalink = get_home_url() . '/' . $post->post_name . '/';

    $cats = get_the_category($post->ID);
    $subcats = array();
    foreach( $cats as $cat ) {
        $cat = get_category($cat->term_id);
        if($cat->parent) { $subcats[] = sanitize_title($cat->name); }
    }
    if($subcats) {
        foreach($subcats as $subcat) {
            $subcat = $subcat.'/';
            $permalink = str_replace($subcat, "", $permalink);
        }
    }


    break;
}

return $permalink;}

It's working fine but there is still a little problem with the code.

If I have an URL like this:

www.myblog.com/parentcategory/nameofchildcategory/slugpost

I will get this:

www.myblog.com/parentcategory/slugpost

Which is exactly what I want.

But if I have an URL like this:

www.myblog.com/parentcategory/nameofchildcategory/slugpost-with-nameofchildcategory

I will get this:

www.myblog.com/parentcategory/slugpost-with- (mssing the end of the slug)

...and a 404 page for every link to this article.

So the problem is that when the child category text appears in the slug's post, the code will also remove this part of the URL.

Anyone have an idea on how to solve this?

Thanks in advance!


Solution

  • Try delimiting both ends of the slug, like:

            foreach ($subcats as $subcat) {
                $permalink = str_replace('/'.$subcat.'/', '/', $permalink);
            }