I have a structure like this for my custom post types:
domain/member/member-name/book/book-name
Basically, I have a custom post type of member, and the member-name is the post. What I want to do is pass a variable called books, but I can't get my code to work.
I've based my solution on one that has previously been asked on here but my structure is different, and I've googled and googled to no avail. I really cant get my head around rewrite structures either!
function add_book_rewrite() {
add_rewrite_tag('%book_name%','([^&]+)');
}
add_action( 'init', 'add_book_rewrite' );
function add_book_rewrite_rules() {
add_rewrite_rule('^member/([^/]*)/book/([^/]*)/?','index.php?post_type=member&name=$matches[2]&book_name=$matches[4]','top');
}
add_action( 'init', 'add_book_rewrite_rules' );
add_filter( 'query_vars', 'add_query_var' );
function add_query_var( $query_vars ) {
$query_vars[] = 'book_name';
return $query_vars;
}
echo 'Book is '.get_query_var('book_name');
Any pointers on this would be received with gratitude
Thanks
I have a structure like this for my custom post types:
domain.com/member/member-name/book/book-name
Basically, I have a custom post type of member, and the member-name is the post. What I want to do is pass a variable called books, but I can't get my code to work.
I've based my solution on one that has previously been asked on here but my structure is different, and I've googled and googled to no avail. I really cant get my head around rewrite structures either!
function add_book_rewrite() {
add_rewrite_tag('%book_name%','([^&]+)');
}
add_action( 'init', 'add_book_rewrite' );
function add_book_rewrite_rules() {
add_rewrite_rule('^member/([^/]*)/book/([^/]*)/?','index.php?post_type=member&name=$matches[2]&book_name=$matches[4]','top');
}
add_action( 'init', 'add_book_rewrite_rules' );
add_filter( 'query_vars', 'add_query_var' );
function add_query_var( $query_vars ) {
$query_vars[] = 'book_name';
return $query_vars;
}
echo 'Book is '.get_query_var('book_name');
Any pointers on this would be received with gratitude
Thanks
First, adding a rewrite tag and a query var is redundant, adding the tag adds the query var.
Second, $matches
corresponds to each regex pattern you have in your rule, so it should be $matches[1]
and $matches[2]
, not 2 and 4.
Last, for a single member
, you can just set the member
query var.
add_rewrite_rule(
'^member/([^/]*)/book/([^/]*)/?',
'index.php?member=$matches[1]&book_name=$matches[2]',
'top'
);
Untested, but should get you going in the right direction. Also check out this rewrite analyzer plugin to help you construct your rewrite rule.