Try this. Here is the full code that you can add to your functions.php
file:
// Add custom rewrite rules
function add_custom_rewrite_rules() {
add_rewrite_rule(
'^category/([0-9]+)/?$',
'index.php?term_id=$matches[1]',
'top'
);
flush_rewrite_rules(false); // Temporarily set this to true to flush rules, then set back to false
}
add_action('init', 'add_custom_rewrite_rules');
// Add term_id to query vars
function add_query_vars($vars) {
$vars[] = 'term_id';
return $vars;
}
add_filter('query_vars', 'add_query_vars');
// Redirect to the correct category page
function custom_category_redirect() {
if (get_query_var('term_id')) {
$term_id = intval(get_query_var('term_id'));
$term = get_term_by('id', $term_id, 'product_cat');
if ($term) {
$url = get_term_link($term, 'product_cat');
if (!is_wp_error($url)) {
wp_redirect($url, 301);
exit;
}
}
}
}
add_action('template_redirect', 'custom_category_redirect');
// Flush rewrite rules when necessary
// Note: Remember to remove this line after the first load to prevent unnecessary flushing
flush_rewrite_rules(true);
Important Notes:
-
Rewrite Rules and Permalinks: Be cautious when modifying rewrite rules and flushing them. Flushing rewrite rules too frequently can affect site performance.
-
Permanent Redirects: The wp_redirect function with a 301 status code is used to permanently redirect the URL. If you intend this to be a temporary change, consider using a 302 status code instead.
-
Testing: Thoroughly test this code in a staging environment before applying it to a live site to ensure it doesn’t interfere with other functionality.
By following these steps, you will be able to change the category URL structure to use term_id
and still display the correct category page in WooCommerce.