Home > Blockchain >  how to add custom url rewrite ie from query string url to pretty url in wordpress using add_rewrite_
how to add custom url rewrite ie from query string url to pretty url in wordpress using add_rewrite_

Time:10-30

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'); 

CodePudding user response:

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/

CodePudding user response:

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;
}
  • Related