Skip to content

Instantly share code, notes, and snippets.

@maciejbis
Created July 25, 2018 08:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save maciejbis/0724d59a543a4ea0d40f16af6dafe91d to your computer and use it in GitHub Desktop.
Save maciejbis/0724d59a543a4ea0d40f16af6dafe91d to your computer and use it in GitHub Desktop.
Use highest & lowest product category slug in Products & Product categories default permalinks
<?php
function pm_use_highest_level_slug_posts($replacement, $replacement_term, $post_object, $terms, $taxonomy, $native_uri) {
if(!empty($post_object->post_type) && $post_object->post_type == 'product' && !empty($replacement_term->term_id) && !$native_uri) {
$term_ancestors = (array) get_ancestors($replacement_term->term_id, $taxonomy);
$top_ancestor_id = (!empty($term_ancestors)) ? end($term_ancestors) : false;
if($top_ancestor_id) {
$top_ancestor = get_term((int) $top_ancestor_id, $taxonomy);
$replacement = "{$top_ancestor->slug}/{$replacement_term->slug}";
}
}
return $replacement;
}
add_filter('permalink_manager_filter_term_slug', 'pm_use_highest_level_slug_posts', 9, 6);
function pm_use_highest_level_slug_terms($replacement, $replacement_term) {
if(!empty($replacement_term->taxonomy) && $replacement_term->taxonomy == 'product_cat') {
$term_ancestors = (array) get_ancestors($replacement_term->term_id, $replacement_term->taxonomy);
$top_ancestor_id = (!empty($term_ancestors)) ? end($term_ancestors) : false;
if($top_ancestor_id) {
$top_ancestor = get_term((int) $top_ancestor_id, $taxonomy);
$replacement = "{$top_ancestor->slug}/{$replacement_term->slug}";
}
}
return $replacement;
}
add_filter('permalink_manager_filter_default_term_slug', 'pm_use_highest_level_slug_terms', 9, 2);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment