Skip to content

Instantly share code, notes, and snippets.

@jdhobbsuk
Created July 27, 2015 10:49
Show Gist options
  • Save jdhobbsuk/7167160fa77c5239f5fb to your computer and use it in GitHub Desktop.
Save jdhobbsuk/7167160fa77c5239f5fb to your computer and use it in GitHub Desktop.
CPT using taxonomy in permalink
<?php
// Make CPT use taxonomy permalink
//--------------------------------------
add_filter('post_type_link', '<CPT>_permalink_filter_function', 1, 3);
function <CPT>_permalink_filter_function( $post_link, $id = 0, $leavename = FALSE ) {
if ( strpos('%<TAXONOMY>%', $post_link) === 'FALSE' ) {
return $post_link;
}
$post = get_post($id);
if ( !is_object($post) || $post->post_type != '<CPT>' ) {
return $post_link;
}
$terms = wp_get_object_terms($post->ID, '<TAXONOMY>');
if ( !$terms ) {
return str_replace('<CPT>/%<TAXONOMY>%/', '', $post_link);
}
return str_replace('%<TAXONOMY>%', $terms[0]->slug, $post_link);
}
// this is the 'rewrite' param inside your register_post_type() function
'rewrite' => array( 'slug' => '<CPT>/%<TAXONOMY>%', 'with_front' => false ),
?>
@jdhobbsuk
Copy link
Author

Swap out the and with the indentifier of your CPT / taxonomy.
Refresh permalinks afterwards.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment