0

I have a page called "People" with a custom template that takes in a variable called name:

example.com/people/?name=FirstLast

What I want is this:

example.com/people/FristLast

I know I need to use the add_rewrite_rule and add_rewrite_tag calls but I'm not sure how to achieve my desired result. I've tried this but I get a php error:

add_rewrite_rule('^people/([^/]*)/?','index.php?name=$matches[1]','top');
add_rewrite_tag('%name%','([^&]+)');

The error I get is: "Fatal error: Call to a member function add_rule() on a non-object"

I think I'm on the right path. I'm very knowledgeable with WP but this is my first attempt to the rewrite rule.

Thanks!

----- EDIT ----- I've updated the code. I no longer get an error but nothing "happens"

function rewrite_rule_people() {
    global $wp_rewrite;
    add_rewrite_tag('%name%','([^/]*)');
    add_rewrite_rule('^people/([^/]*)','index.php?page_id=42602&name=$matches[1]','top');
    $wp_rewrite->flush_rules();
}
add_action( 'init', 'rewrite_rule_people' );

going to /people/?name=JohnSmith doesn't change the url to /people/JohnSmith

  • Be careful about using $wp_rewrite->flush_rules() as it's pretty hefty, programmatically speaking. You can achieve the same effect by going to Settings->Permalinks in the admin screens and saving your Permalink settings. See codex.wordpress.org/Rewrite_API/flush_rules – Pat J Apr 11 '13 at 16:53
0

You need to use your page id of "People" page. If i assume it is 12 then this will do,

add_rewrite_rule('^people/([^/]*)/?','index.php?page_id=12&name=$matches[1]','top');
  • added the page id (and some additional code). Now I'm no longer getting an error but the url doesn't respond to the rewrite. (see edit) – dcp3450 Apr 11 '13 at 15:59
  • @dcp3450 Try adding "/?" at end of rewrite rule – Rajeev Vyas Apr 11 '13 at 16:02
  • 1
    @dcp3450 you no longer need to go to "people?name=xxx", after adding rewrite rule, you have to use new url "people/JohnSmith" – Rajeev Vyas Apr 11 '13 at 16:07
  • adding the "/?" worked. thanks! – dcp3450 Apr 11 '13 at 17:50
  • Adding /? to the end simply makes the trailing slash in the request an optional part of the URL, ie. people/SomePerson and people/SomePerson/ are both valid, without the trailing slash only the former is accounted for. Stated for anyone curious to know what that part of the code does. – t31os Apr 12 '13 at 8:37

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.