I'm stuck in need of a rewrite rule. I have set up a custom post type for 'Books', each book has a repeatable field (using ACF Pro) for chapters.
I have added a query_var
for chapter
using the code below...
// Add chapter to query vars array
function add_query_vars_filter( $vars ){
$vars[] = "chapter";
return $vars;
}
add_filter( 'query_vars', 'add_query_vars_filter' );
On the single-books.php
template page, I have a code to capture the query_var
and either display the book overview or the chapter meta fields...
if (get_query_var('chapter') == '') {
// show book title and content
} elseif (get_query_var('chapter') >= 1) {
$chapter_no = (get_query_var( 'chapter', 1 ) - 1); //minus one as first array row has index of 0.
$rows = get_field('chapter'); // get all the rows
$chapter = $rows[$chapter_no]; // get the row given from query_var
// show chapter fields from ACF array.
// $chapter['title']
// $chapter['content']
// $chapter['image']
};
So the url for Chapter 1 would look like this...
www.example.com/books/book-title/?chapter=1
This works fine, but for SEO purposes I want the url to look prettier, like the example below...
www.example.com/books/book-title/1/chapter-title/
I've looked at the codex and tried the following...
function custom_rewrite_basic() {
add_rewrite_rule('^books/([^/]*)/([0-9]+)/?', 'index.php?post_type=books&chapter=$matches[1]', 'top');
}
add_action('init', 'custom_rewrite_basic');
I'm not getting anything from it, not really sure what I need to do/if it's possible. Can anyone point me in the right direction, or show me how to create the rewrite rule.
Thanks.
book
andbooks
, what is the actual post type slug it is registered with? Your rule doesn't set the specific book that's requested, and the chapter title slug segment is missing.books
that should also saysingle-books.php
. I'm not sure how to set the specific book. I missed off the title segment as I was just trying to get it to work by pulling in the chapter number before I figures out how to get the chapter title in there from the custom field.