Skip to content

Instantly share code, notes, and snippets.

@MjHead
Last active October 18, 2022 18:51
Show Gist options
  • Save MjHead/9f091001abddb5c5a598408930d43942 to your computer and use it in GitHub Desktop.
Save MjHead/9f091001abddb5c5a598408930d43942 to your computer and use it in GitHub Desktop.
This code allows you to add parent term slug into single post URL
add_filter( 'register_post_type_args', 'je_change_post_type_rewrite_slug', 10, 2 );
/**
* Change post type rewirte
* Where:
* - apartments - is a post type slug. Replace is with your actual slug.
* - %locations% - is a placeholder for taxonomy term in URL.
*
* @param array $args
* @param string $post_type_name
* @return array
*/
function je_change_post_type_rewrite_slug( $args, $post_type_name ) {
if ( 'apartments' !== $post_type_name ) {
return $args;
}
$args['rewrite'] = array(
'slug' => 'apartments/%locations%',
'with_front' => false
);
$args['has_archive'] = 'apartments';
return $args;
}
add_filter( 'post_type_link', 'je_change_permalinks', 1, 2 );
/**
* Change post permalink
* Where:
* - apartments - is a post type slug. Replace is with your actual slug.
* - locations in wp_get_object_terms - is a taxonomy slug to get terms from. Replace it with your actual slug.
* - %locations% - is a placeholder for term. Should be the same as in previous function.
* - locations in second str_replace - is a default part of URL, if no terms of needed taxonomy is attached to post.
*
* @param string $post_link
* @param WP_Post $post
* @return string
*/
function je_change_permalinks( $post_link, $post ) {
if ( ! is_object( $post ) || 'apartments' !== $post->post_type ) {
return $post_link;
}
$terms = wp_get_object_terms( $post->ID, 'locations' );
if ( ! empty( $terms ) && ! is_wp_error( $terms ) ) {
return str_replace( '%locations%' , $terms[0]->slug, $post_link );
} else {
return str_replace( '%locations%' , 'locations', $post_link );
}
}
@liranop
Copy link

liranop commented Oct 18, 2022

How can I make it work for hierarchical taxonomy and not just the first term (apartments/parent-category/child-category/example)

I have this gits: https://gist.github.com/liranop/118be6fa5654d07dfa76298d312e29a4

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