views:

47

answers:

1

Hi. I have a WP page named Book (/book/) which displays a book in various languages. The language and chapter variables are passed as query variables. So the URL structure looks like:

/book/english/ (This displays a list of chapters in English) /book/english/foreword/ (This displays the Foreword of the book in English)

Here is what I have come up with:

add_action('init', 'book_init');
add_filter('rewrite_rules_array', 'book_rewrite_rules_array');
add_filter('query_vars', 'book_query_vars');

function book_init() {
 global $wp_rewrite;
 $wp_rewrite->flush_rules();
}
function book_rewrite_rules_array($rewrite_rules) {
 global $wp_rewrite;
 $custom['(book)/(.+)/(.+)$'] = 'index.php?pagename=$matches[1]&book_language=$matches[2]&book_chapter=$matches[3]';
 $custom['(book)/(.+)$'] = 'index.php?pagename=$matches[1]&book_language=$matches[2]';
 return $custom + $rewrite_rules;
}
function book_query_vars($query) {
 array_push($query, 'book_language', 'book_chapter');
 return $query;
}

Everything is working but the problem is that, the rewrite rules I have added are also catching /book/feed/ which I don't want. So I am looking for an expression which would negate feed from '(book)/(.+)/(.+)$' and '(book)/(.+)$'

Also I want to know, if assume the query variables supplied are invalid, which filter should I use to check this in and how can I stop WP from continuing and instead make it send a 404 error and have it show the 404 page?

+1  A: 

You should be able to exclude 'feed' from your route using a negative lookahead, something like this: (book)/(?!feed$)(.+)$.

As to the second part of your question, you can hook into the request filter examine the query variables and then add an 'error' value to the variables array to cause Wordpress to throw a 404 error.

add_filter('request', 'book_request');
function book_request($vars) {
     if (!in_array($vars['book_language'], array('english', 'spanish'))) {
         $vars['error'] = '404';
     }
     return $vars;
}
Richard M