1

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;
}
  • Maybe it would be easier to accomplish it using the rewrite rules in .htaccess? mediatemple.net/community/products/dv/204643270/… You can set up a rewrite rule for this specific slug to trick wordpress that it is xxx/slug – NatWeb Solutions Nov 20 '19 at 9:28
  • Don't you think .htaccess is best used for search engines? I would prefer doing it in the functions.php to avoid issues. – Elaine Byene Nov 20 '19 at 9:56
  • Elaine entire WordPress would not function without .htacces as it relies on redirecting every URL back to index.php. .htaccees can be used for many things starting from rewrite rules and ending in tweaking server parameters – NatWeb Solutions Nov 20 '19 at 10:03

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.