Wordpress url rewriting - nice URL with name from

2019-06-09 07:06发布

问题:

I'm developing a Wordpress site, that loads most of the content from SugarCRM.

Currently I get the boats item on URL like

http://domain.com/boats/?id=123456789

but I would like to have nice URL's, with the name that is loaded from SugarCRM, like

http://domain.com/boats/this-is-boat-name

Is there a way to do this without creating custom post type and a post for each item in Wordpress?

回答1:

You could try using add_rewrite_rule.

Have the user access the page via the url domain.com/boats/12345/this-is-boat-name/

Then you can pick up the ID in PHP as if it were a $_GET query string.

First the rewrite rules;

$rule = '^(boats)/([^/]*)/([^/]*)/?';
$write = 'index.php?name=boats&id=$matches[1]&pagename=$matches[1]';
add_rewrite_rule($rule, $write, 'top');

And then the filter so you can access the page URL as like a query string

add_filter('query_vars', 'foo_my_query_vars');
function foo_my_query_vars($vars){
    $vars[] = 'id';
    $vars[] = 'pagename';
    return $vars;
}

Then, on the page template in your theme, you can pick up the (invisible) query string values like:

$id = get_query_var('id');
$pagename = get_query_var('pagename');
echo $id.' '.$pagename;

Make sure to flush the permalinks after adding the rewrite rules and filter into your functions.php