I used the following functions to solve this problem.
//This adds a custom query variable to the permalink
function add_custom_query_var( $vars ){
$vars[] = "shop_name";
return $vars;
}
add_filter( 'query_vars', 'add_custom_query_var' );
function add_rewrite_rules($aRules) {
$aNewRules = array('shop/([^/]+)/?$' => 'index.php?pagename=shop&shop_name=$matches[1]');
$aNewRules2 = array('shop/([^/]+)/gallery/?$' => 'index.php?post_type=gallery');
$aRules = $aNewRules + $aNewRules2 + $aRules;
return $aRules;
}
add_filter('rewrite_rules_array', 'add_rewrite_rules');
//Here we create a custom permalink structure and replace the shop_name with custom user feild value
function tdd_permalinks($permalink, $post, $leavename){
$no_data = get_the_author_meta('ID');;
$post_id = $post->ID;
if($post->post_type != 'gallery' || empty($permalink) || in_array($post->post_status, array('draft', 'pending', 'auto-draft'))) return $permalink;
$var1 = get_the_author_meta('shop_name');
$var1 = sanitize_title($var1);
if(!$var1) { $var1 = $no_data; }
$permalink = str_replace('%shop_name%', $var1, $permalink);
return $permalink;
}
add_filter('post_type_link', 'tdd_permalinks', 10, 3);
function rewrite_flush(){
global $wp_rewrite;
$gallery_structure="/shop/%shop_name%/gallery/%gallery%";
$wp_rewrite->add_rewrite_tag("%gallery%", '([^/]+)', "gallery=");
$wp_rewrite->add_rewrite_tag("%shop_name%", '([^/]+)', "shop_name=");
$wp_rewrite->add_permastruct('gallery', $gallery_structure, false);
$wp_rewrite->flush_rules();
}
add_action('init','rewrite_flush');