WordPress changing permalinks for two categories

My WordPress permalink structure is /%postname%/ and I want to change that for the posts in two different categories. This is the code:

/* Rewriting permalink structure for posts in category 'Blog' */
add_filter( 'post_link', 'custom_permalink', 10, 2 );
function custom_permalink( $permalink, $post ) {
// Get the categories for the post
  $categories = wp_get_post_categories( $post->ID );
  foreach ( $categories as $cat ) {
    $post_cat    = get_category( $cat );
    $post_cats[] = $post_cat->slug;
  }

// Check if the post have 'blog' category
// Assuming that your 'Blog' category slug is 'blog'
// Change 'blog' to match yours
if ( in_array( 'blog',$post_cats ) ) {
    $permalink = trailingslashit( home_url( 'blog/' .  $post->post_name ) );
}
return $permalink;
}

 add_filter( 'rewrite_rules_array', 'custom_rewrite_rule' );
function custom_rewrite_rule( $rules ) {
  $new_rules = array(
    'blog/([^/]+)/trackback/?$' => 'index.php?name=$matches[1]&tb=1',
    'blog/([^/]+)/feed/(feed|rdf|rss|rss2|atom)/?$' => 'index.php?name=$matches[1]&feed=$matches[2]',
    'blog/([^/]+)/(feed|rdf|rss|rss2|atom)/?$' => 'index.php?name=$matches[1]&feed=$matches[2]',
    'blog/([^/]+)/comment-page-([0-9]{1,})/?$' => 'index.php?name=$matches[1]&cpage=$matches[2]',
    'blog/([^/]+)(/[0-9]+)?/?$' => 'index.php?name=$matches[1]&page=$matches[2]'
  );

$rules = $new_rules + $rules;
return $rules;
}

it’s working well for the first category, but when I use the same code for the second category in functions.php, the site is not loading properly, showing a blank page. It’s like just working for one of them, not both at the same time. It’s weird.

Read More

Any thoughts?

Related posts