0

I have a bible page which is page_id of 135 and I am trying to create multiple WordPress rewrite rules. I am trying to obtain something like either of the following:

  • website/bible/nasb
  • website/bible/nasb/Genesis
  • website/bible/nasb/Genesis/1

I want to be able to access the query parameters via WordPress's get_query_var() function. However, all of the parameters seem to be kept in get_query_var('version'). They won't split into 3 different parameters. It puts "nasb/Genesis/1" into the version parameter.

I want to be able to access the parameters like this:

  • get_query_var('version')
  • get_query_var('book')
  • get_query_var('chapter')

Here is my code:

add_action( 'init' , function() {

add_rewrite_tag('%version%','([^&]+)');
add_rewrite_tag('%book%','([^&]+)');
add_rewrite_tag('%chapter%','([^&]+)');

add_rewrite_rule(
    '^bible/(.+)/?$',
    'index.php?page_id=135&version=$matches[1]',
    'top'
);

add_rewrite_rule(
    '^bible/(.+)/(.+)/?$',
    'index.php?page_id=135&version=$matches[1]&book=$matches[2]',
    'top'
);

add_rewrite_rule(
    '^bible/(.+)/(.+)/(.+)/?$',
    'index.php?page_id=135&version=$matches[1]&book=$matches[2]&chapter=$matches[3]',
    'top'
);  

flush_rewrite_rules();

} );

Thank you.

P.S.

I currently have my permalinks set to post name which cleans up the url, so that is not an issue.

2 Answers 2

1

The pattern (.+) matches any character, including the slash, so any combo of parameters will always match your first rule, with anything that follows being passed as the version query var. Change all instances of (.+) to ([^/]+) to match all characters except the slash.

1
  • Thank you. I am not good at regexes at all. It works perfectly in combination with TheDeadMedic's answer. Oct 10, 2015 at 20:16
0

You don't want rewrite tags - these are only useful for defining permalink structures. Instead, keep your rules and add the parameters as query vars:

function wpse_205120_query_vars( $qvars ) {
    $qvars[] = 'version';
    $qvars[] = 'chapter';
    $qvars[] = 'bible';
    return $qvars;
}

add_filter( 'query_vars', 'wpse_205120_query_vars_query_vars' );

You'll also want to get rid of that flush_rewrite_rules() once it's all working.

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.