Post url rewriting for posts with certain category

generate_rewrite_rules didn’t work for me at all and I found posts on forums where others were having the same issue. Adding to the rewrite_rules_array did work. Below is the solution.

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 == "Shop" )
  {
      $permalink = trailingslashit( home_url('shop/' . $post->post_name ) );
  }
  return $permalink;
}

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

function wp_insertMyRewriteRules($rules)
{
  $newrules = array();
  $newrules['^shop/(.*)$'] = 'index.php?name=$matches[1]';
  return $newrules + $rules;
}