skip to Main Content

I need some help to find the solution to remove the url date only from posts in a specific category.

I have my permalinks settings like this:

 /%year%/%monthnum%/%day%/%category%/%postname%/

A category-x post has the following url:

http://mysite/2021/08/25/category-x/post-name/

I need only for category-x posts, the url looks like this:

http://mysite/category-x/post-name/

The other posts would remain with the date in the url.

I tried to do something with the rewrite_rules_array and post_link filters, with no success.

How could I solve it?

2

Answers


  1. Chosen as BEST ANSWER

    I solved it this way:

    add_filter( 'post_link', function( $permalink, $post, $leavename ){
        $category = get_the_category($post->ID);    
        if (  !empty($category) && $category[0]->slug == "category-x" ) {
            $permalink = trailingslashit( home_url('/category-x/'. $post->post_name . '/' ) );
        }
        return $permalink;
    }, 10, 3 ); 
    
    add_action('generate_rewrite_rules',function( $wp_rewrite ) {
        $new_rules['^category-x/([^/]+)/?$'] = 'index.php?name=$matches[1]';
        $wp_rewrite->rules = $new_rules + $wp_rewrite->rules;
        return $wp_rewrite;
    });
    

    Thank you anyway!


  2. Changing category base prefix
    enter image description here

    Try Redirects After Changing Category Base Prefix

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search