Last active
August 15, 2024 23:27
-
-
Save vovadocent/7995dd669e606ec039deb8cb86214eed to your computer and use it in GitHub Desktop.
Custom slug and category slugs in product url.php
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/* filter to get "services" in product categories, child categories, and singe product pages correctly */ | |
// /services/%product_cat%/ - Product base permalink settings | |
// services - Product Category base permalink settings | |
add_filter('rewrite_rules_array', function( $rules ) { | |
$new_rules = array( | |
'services/([^/]*?)/page/([0-9]{1,})/?$' => 'index.php?product_cat=$matches[1]&paged=$matches[2]', | |
'services/([^/]*?)/([^/]*?)/page/([0-9]{1,})/?$' => 'index.php?product_cat=$matches[2]&paged=$matches[3]', | |
'services/([^/]*?)/?$' => 'index.php?product_cat=$matches[1]', | |
'services/([^/]*?)/([^/]*?)/?$' => 'index.php?product_cat=$matches[2]', | |
); | |
return $new_rules + $rules; | |
}); | |
add_filter('request', function( $vars ) { | |
global $wpdb; | |
if (!empty($vars['pagename']) || !empty($vars['category_name']) || !empty($vars['name']) || !empty($vars['attachment'])) { | |
$slug = !empty($vars['pagename']) ? $vars['pagename'] : (!empty($vars['name']) ? $vars['name'] : (!empty($vars['category_name']) ? $vars['category_name'] : $vars['attachment'] ) ); | |
$new_slug = $vars["product_cat"] . "/$slug"; | |
$cat = getCategoryByPath($new_slug, 'product_cat'); | |
if($cat){ | |
$old_vars = $vars; | |
$vars = array('product_cat' => $new_slug); | |
if (!empty($old_vars['paged']) || !empty($old_vars['page'])) | |
$vars['paged'] = !empty($old_vars['paged']) ? $old_vars['paged'] : $old_vars['page']; | |
} | |
}elseif (!empty($vars['product_cat'])) { | |
$slug = $vars['product_cat']; | |
$cat = getCategoryByPath($slug, 'product_cat', 0); | |
if(!$cat && get_page_by_path( $slug, OBJECT, 'product')){ | |
$vars["product"] = $slug; | |
$vars["post_type"] = "product"; | |
$vars["name"] = $slug; | |
} | |
} | |
return $vars; | |
}); | |
function getCategoryByPath($path, $tax, $check_parent = 1 ){ | |
global $wpdb; | |
$slugs = explode('/', $path); | |
$parent = 0; | |
foreach ($slugs as $k => $slug) { | |
$args = array( | |
'hide_empty' => false, | |
'slug' => $slug, | |
); | |
if($check_parent) | |
$args['parent'] = $parent; | |
$terms = $terms = get_terms($tax, $args); | |
if($terms && count($terms) == 1){ | |
$term = $terms[0]; | |
$parent = $term->term_id; | |
if($k == count($slugs) - 1) | |
return $term; | |
}else{ | |
break; | |
} | |
} | |
return false; | |
} | |
/* end of filter */ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment