Skip to content

Instantly share code, notes, and snippets.

@khleomix
Created March 7, 2023 18:44
Show Gist options
  • Save khleomix/0ae16bb250f01b62eb5a629ab4c490d4 to your computer and use it in GitHub Desktop.
Save khleomix/0ae16bb250f01b62eb5a629ab4c490d4 to your computer and use it in GitHub Desktop.
Add post type slug before taxonomy slug for post link
<?php
/**
* Create the WordPress rewrite rule to handle third level slugs for videos.
*
*/
function video_cpt_generating_rule( $wp_rewrite ) {
$rules = [];
$terms = get_terms( [
'taxonomy' => 'series',
'hide_empty' => false,
] );
$post_type = 'video';
foreach ( $terms as $term ) {
$rules['video-series/' . $term->slug . '/([^/]*)$'] = 'index.php?post_type=' . $post_type. '&series=$matches[1]&name=$matches[1]';
}
// merge with global rules
$wp_rewrite->rules = $rules + $wp_rewrite->rules;
}
add_filter( 'generate_rewrite_rules', 'video_cpt_generating_rule' );
/**
* Change series slug to show rewrite rule.
*
*/
function video_change_link( $permalink, $post ) {
if ( $post->post_type == 'video' ) {
$series_terms = get_the_terms( $post, 'series' );
$term_slug = '';
if ( ! empty( $series_terms ) ) {
foreach ( $series_terms as $term ) {
$term_slug = $term->slug;
break;
}
}
$permalink = get_home_url() ."/video-series/" . $term_slug . '/' . $post->post_name;
}
return $permalink;
}
add_filter( 'post_type_link', 'video_change_link', 10, 2 );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment