Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Only lets the top level term in the permalink structure
<?php
function wpse147453_remove_child_categories_from_permalinks( $permalink, $post, $leavename, $sample ) {
if ( in_array( $post->post_type, array( 'focus_courses' ) ) ) {
// Allow for slug to be editable
$slug = $leavename ? '%' . $post->post_type . '%' : $post->post_name;
// Generate premalink prefix based on post type
$prefix = 'courses';
// add parent term slug
$term_slug = focus_top_term( $post );
// Array of custom permalink tabs
$permalink_tags = array(
'%prefix%',
'%term_slug%',
'%postname%',
);
// Array of permalink values
$permalink_values = array(
$prefix,
$term_slug,
$slug,
);
// Generate the permalink
$permalink = str_replace( $permalink_tags, $permalink_values, '/%prefix%/%term_slug%/%postname%/' );
$permalink = user_trailingslashit( home_url( $permalink ) );
}
return $permalink;
}
add_filter( 'post_type_link', 'wpse147453_remove_child_categories_from_permalinks', 1, 4 );
function focus_top_term( $post ){
$terms = wp_get_object_terms( $post->ID, 'course_categories' );
$plucked = wp_list_pluck( $terms, 'parent' );
// getting parrent term object and it's slug
$term = get_term_by( 'id', absint( $plucked[0] ), 'course_categories' );
$slug = wp_list_pluck( array( $term ), 'slug' );
return $slug[0];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment