Adding rewrite rule dynamically for search results redirecting to 404 URL

We need the search url structure like the below

URL : https://siteurl.com/in/chennai/accountant/

We have already a post url with same structure for single post detail page

URL : https://siteurl.com/in/chennai/accountant/ramesh/

We have added coding like below

add_action( 'init',  function() {
add_rewrite_rule( 'in/([^/]*)/([^/]*)/?', 'index.php?pagename=onwpdocs-pro-category-action=$matches[1]wpdocs-product-cat-id=$matches[2]', 'top' );   
} );

If one is matched another one getting 404 for example if the above code works for search url then the post detail page going to 404 page.

Here are the other codes for beautifying url and redirect url written by us

add_filter( 'query_vars', function( $query_vars ) {

    $query_vars[] = 'directory_type';
    $query_vars[]  ='in_cat';
    $query_vars[]  ='in_loc';
    
    return $query_vars;

} );

Rewrite code

function wp_search_url() {

    global $wp_rewrite;

    $type = get_query_var('directory_type');

    $product = get_query_var('in_cat');
    
    $location = get_query_var('in_loc');

    $parent = get_term_by( 'id', $location, 'at_biz_dir-location' );
    
    $category = get_term_by( 'id', $product, 'at_biz_dir-category' );

    if($parent){
        $parent_region = $parent-slug;
    }

    if($category){
        $parent_category = $category-slug;
    }
    
        $inCategory= get_query_var('in_cat');
        $inLocation= get_query_var('in_loc');
        $directoryType= get_query_var('directory_type');
    

    if ( !empty(get_query_var( 'directory_type' ))) {



        if(!session_id()){

            $_SESSION['incategory'] = $inCategory;
            $_SESSION['inlocation'] = $inLocation;
            $_SESSION['directorytype'] = $directoryType;
        
        }else{

            $_SESSION['incategory'] = $inCategory;
            $_SESSION['inlocation'] = $inLocation;
            $_SESSION['directorytype'] = $directoryType;

        }
        
        wp_redirect( home_url()./on/.$parent_region./.$parent_category./);
        
        exit(); 
        
    }else{
            return;
        }
    
}
add_action( 'template_redirect', 'wp_search_url' );

Please help us to fix this issue. Thanks in advance.

Topic template-redirect wp-redirect urls redirect Wordpress

Category Web

About

Geeks Mental is a community that publishes articles and tutorials about Web, Android, Data Science, new techniques and Linux security.