Created
July 20, 2023 02:53
-
-
Save zuramai/e92b8be71c4ba498c11a79ef0487e620 to your computer and use it in GitHub Desktop.
Plugin series
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/* | |
Plugin Name: Nested Route | |
*/ | |
add_action('init', 'rpt'); | |
function rpt() { | |
// flush_rewrite_rules(); | |
register_post_type('series', [ | |
'label' => 'series', | |
'public' => true, | |
'supports' => ['title', 'editor'], | |
'rewrite' => [ | |
'with_front' => false, | |
'slug' => '/' | |
] | |
]); | |
register_post_type('episode', [ | |
'label' => 'episode', | |
'public' => true, | |
'supports' => ['title', 'editor'] | |
]); | |
add_rewrite_rule("series/(.*?)/episodes/(.*?)[/]?$", 'index.php?series=$matches[1]&episode=$matches[2]', 'top'); | |
} | |
add_action('add_meta_boxes', 'metabox_series'); | |
function metabox_series() { | |
add_meta_box('series', 'Series', 'series_cb', 'episode'); | |
} | |
add_action('save_post', 'save_episode'); | |
function save_episode($post) { | |
if(@$_POST['series_id']) { | |
update_post_meta($post, 'series_id', $_POST['series_id']); | |
} | |
} | |
function series_cb($post) { | |
$q = new WP_Query([ | |
'posts_per_page' => -1, | |
'post_type' => 'series' | |
]); | |
$series_id = get_post_meta($post->ID, 'series_id', true); | |
?> | |
<label for="series_id">Choose Series</label> | |
<select name="series_id" id="series_id"> | |
<?php | |
while($q->have_posts()): $q->the_post(); | |
$checked = $series_id && $series_id !== '' && $series_id == get_the_ID(); | |
?> | |
<option value="<?= get_the_ID() ?>" <?= $checked ? 'selected' : '' ?>><?= get_the_title() ?></option> | |
<?php endwhile ?> | |
</select> | |
<?php | |
} | |
add_action('post_type_link', 'episode_link', 10, 2); | |
function episode_link($link, $post) { | |
if($post->post_type == 'episode') { | |
$meta = get_post_meta($post->ID, 'series_id', true); | |
if(!$meta || $meta == "") return $link; | |
$series = get_post($meta); | |
return home_url("/series/{$series->post_name}/episodes/{$post->post_name}"); | |
} | |
return $link; | |
} | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment