0

I'm designing a theme for a customer. We have only one post for each TvShow, And inside that post, We have all the Seasons and Episodes. (Using meta_post).

Now, I have a ul for filtering seasons and one for filtering episodes, Like Show 1st Season, Episode 3. But that needs adding rules to posts (I don't want to use js for this).

Something like: www.example.com/tvshow-name/season-3/episode4/

Apparently we cannot add rule to posts using add_rewrite_rule (Believe me, I tried a lot!), And I don't know how can I add something to address of the post like pages.

Something like: add_rewrite_rules('/([^/]+)/season-([0-9]+)/episode-([0-9]+)/?$', 'index.php?name=$matches[1]&season=$matches[2]&episode=$matches[3])

The problem is: After going to www.example.com/tvshow-name/season-3/episode4/, It redirects back to www.example.com/tvshow-name/, And I get no season or episode!

Is this possible, Or I have to create a page and create my single post template on that? (It's very ugly, But last hope)

2 Answers 2

1

You're almost there. You need to add the season and episode query vars to the array of recognized vars. Note the small change to your regex as well-

function wpd_add_my_rule(){
    add_rewrite_rule(
        '^([^/]+)/season-([0-9]+)/episode-([0-9]+)/?$',
        'index.php?name=$matches[1]&season=$matches[2]&episode=$matches[3]',
        'top'
    );
}
add_action( 'init', 'wpd_add_my_rule' );

function wpd_add_query_vars( $query_vars ) {
    $query_vars[] = 'season';
    $query_vars[] = 'episode';
    return $query_vars;
}
add_filter( 'query_vars', 'wpd_add_query_vars' );

You can use get_query_var() in the template to fetch the values.

3
  • Thanks, I forgot to add the real problem to my question. I used your solution, But still doesn't work. See "The problem is:" In my question please.
    – Shantia
    Commented Jun 1, 2017 at 7:59
  • Oh, I had assumed it was the built in post, I missed that it was a custom post type.
    – Milo
    Commented Jun 1, 2017 at 12:55
  • That was my bad, I didn't know it's important for doing such a thing. sorry.
    – Shantia
    Commented Jun 1, 2017 at 13:00
0

It's not pretty that I answer my own problem, But for others that maybe have the same issue:

I just had to add post_type in my add_rewrite_rule

 add_rewrite_rule(
    '^([^/]+)/season-([0-9]+)/episode-([0-9]+)/?$',
    'index.php?post_type=tvseries&name=$matches[1]&season=$matches[2]&episode=$matches[3]"',
    'top'
);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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