How to remove specific category from URL in WordPress

Question

My custom structure permalink is set as shown below and category base is set to .

/%category%/%postname%/

My current URL structure is this:

http://example.com/aaa/slug
http://example.com/bbb/slug
http://example.com/ccc/slug
http://example.com/xxx/slug

There are many categories and one of them is xxx. I want the URLs for this particular category to change from http://example.com/xxx/slug to http://example.com/slug

How do I go about doing this? I manage to get the URL the way I want but it’s throwing me a 404 error.

Here’s the code:

add_filter( 'post_link', 'custom_permalink', 10, 3 );
function custom_permalink( $permalink, $post, $leavename ) {
    // Get the categories for the post
    $category = get_the_category($post->ID); 
    if (  !empty($category) && $category[0]->cat_name == "xxx" ) {
        $permalink = trailingslashit( home_url('/'. $post->post_name .'-'. $post->ID .'/' ) );
    }
    return $permalink;
}
add_action('generate_rewrite_rules', 'custom_rewrite_rules');
function custom_rewrite_rules( $wp_rewrite ) {
    // This rule will will match the post id in %postname%-%post_id% struture
    $new_rules['^([^/]*)-([0-9]+)/?'] = 'index.php?p=$matches[2]';
    $wp_rewrite->rules = $new_rules + $wp_rewrite->rules;
    return $wp_rewrite;
}

I also tried this without success:

add_filter( 'post_link', 'custom_permalink', 10, 3 ); 
add_filter('rewrite_rules_array','wp_insertMyRewriteRules');
add_filter('init','flushRules'); 

function custom_permalink( $permalink, $post, $leavename ) {
  $category = get_the_category($post->ID); 
  if (  !empty($category) && $category[0]->cat_name == "Uncategorized" )
  {
      $permalink = trailingslashit( home_url('/' . $post->post_name ) );
  }
  return $permalink;
}

function flushRules(){
  global $wp_rewrite;
  $wp_rewrite->flush_rules();
}

function wp_insertMyRewriteRules($rules)
{
  $newrules = array();
  $newrules['^/(.*)$'] = 'index.php?name=$matches[1]';
  return $newrules + $rules;
}
0
, , , Elaine Byene 3 weeks 0 Answers 15 views 0

Leave an answer