I have two custom post types:
- Programs, which have the URL structure: /program/[program-name]/
- Episodes, which have the URL structure: /program/[program-name]/episode/[episode-name]
Episodes use a custom field to tell WordPress which program it belongs to. I’ve got this part working just fine.
However, the program page shows only basic information about the program and three featured episodes. I need to create an archive page for each program that lists all the episodes.
Based on how I’ve set things up, I believe I need an archive page for episodes that use the following URL structure: /program/[program-name]/episodes. I know I can create a file called archive-episodes.php to get started. However, I’m having trouble with determining how to modify the URL to suit my needs, especially in light of what I’ve already done.
Here are the functions I’ve used to accomplish what I have so far:
// Create the custom post types
function create_cpts() {
// Programs
register_post_type('programs',
array(
'labels' => array(
'name' => __( 'Programs' ),
'singular_name' => __( 'Program' ),
'edit_item' => __( 'Edit Program' ),
'add_new' => __( 'Add New Program' ),
'add_new_item' => __( 'Add New Program' )
),
'public' => true,
'has_archive' => true,
'rewrite' => array(
'with_front' => false,
'slug' => 'program'
),
'taxonomies' => array('program-category'),
'supports' => array('thumbnail', 'title', 'editor', 'excerpt'),
'menu_position' => 6,
'menu_icon' => 'dashicons-video-alt2'
)
);
// Episodes
register_post_type('episodes',
array(
'labels' => array(
'name' => __( 'Episodes' ),
'singular_name' => __( 'Episode' ),
'edit_item' => __( 'Edit Episode' ),
'add_new' => __( 'Add New Episode' ),
'add_new_item' => __( 'Add New Episode' )
),
'public' => true,
'has_archive' => false,
'rewrite' => array(
'with_front' => false,
'slug' => 'program/%program%/episode'
),
'supports' => array('thumbnail', 'title', 'editor', 'excerpt'),
'menu_position' => 7,
'menu_icon' => 'dashicons-media-video'
)
);
}
add_action( 'init', __NAMESPACE__ . '\\create_cpts' );
// Custom program permalink for episodes
function add_directory_rewrite() {
global $wp_rewrite;
add_rewrite_tag('%program%', '(.+)');
add_rewrite_rule('^program/(.+)/episode/(.+)/', 'index.php?p=$matches[2]&program=$matches[1]', 'top');
}
add_action('init', __NAMESPACE__ . '\\add_directory_rewrite');
function episode_rewrite($permalink, $post, $leavename) {
if ($post->post_type == 'episodes') {
if ($program = get_field('program', $post->ID)) {
$program = $program->post_name;
} else {
$program = 'default';
}
return str_replace('%program%', $program, $permalink);
} else {
return $permalink;
}
}
add_filter('post_type_link', __NAMESPACE__ . '\\episode_rewrite', 11, 3);
Any help or direction would be greatly appreciated. Thanks.