skip to Main Content

I just need to redirect test.com/buying/properties-for-sale/?property=-north-gorley-11409

to test.com/buying/properties-for-sale/-north-gorley-11409 in wordpress

I have tried the below rewrite but result in 404 page

add_rewrite_rule('/buying/properties-for-sale-salisbury-2/?([^/]*)', 'index.php?pagename=properties-for-sale-salisbury-2&property=$matches[1]', 'top'); 

2

Answers


  1. Chosen as BEST ANSWER

    the code worked worked for me I have founf the smam etype of issue here

    add_action( 'init',  function() {
    
    
    add_rewrite_rule('^(tenants)/([^/]*)/?', 'index.php?pagename=$matches[1]&property=$matches[2]','top');
    add_rewrite_rule('^(buying/properties-for-sale-salisbury-2)/([^/]*)/?', 'index.php?pagename=$matches[1]&property=$matches[2]','top');
    
    add_filter('query_vars', 'foo_my_query_vars');
    });
    
    
    function foo_my_query_vars($vars){
    $vars[] = 'property';
    return $vars;
    }
    

  2. Example to add rewrite rule query as optional,hope it helps.

    function custom_rewrite_rule() {
        add_rewrite_rule('^nutrition/?([^/]*)/?','index.php?page_id=12&food=$matches[1]','top');
    }
    add_action('init', 'custom_rewrite_rule', 10, 0);
    

    The main thing here is to add ? at the start of your regex. Like ?([^/]*)

    Now, you can set a default value for the optional query where you will use the query.

    $food = $wp_query->get( 'food' );
    if( isset($food) && !empty($food) ) {
        $nutrition = $food;
    }else{
        $nutrition = 'strawberry'; //default value
    }
    

    Now you will get the same result for http://example.com/nutrition/strawberry or http://example.com/nutrition/

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search