Я пытаюсь настроить структуру постоянных ссылок для продуктов WooCommerce.
Я пробовал реализовать решение с помощью add_rewrite_rule(), но безуспешно. В настоящее время ссылки генерируются как:
my-website.com/shop/product/product_name-sku
но я хочу, чтобы они были структурированы как:
my-website.com/shop/parent-cat/child-cat/product_name-sku
Я изо всех сил пытаюсь понять, как объединить get_terms() с родительскими и дочерними категориями.
Мой фрагмент кода:
add_filter('post_type_link', 'custom_product_permalink', 1, 2);
function custom_product_permalink($link, $post) {
if ($post->post_type == 'product') {
// Convert the entire URL to lowercase
return strtolower(home_url('shop/product/' . $post->post_name . '-' . get_post_meta($post->ID, '_sku', true) . '/'));
} else {
return $link;
}
}
add_action('init', 'custom_product_permalink_rewrite_rules');
function custom_product_permalink_rewrite_rules() {
add_rewrite_rule(
'shop/product/([^/]+)-([^/]+)/?$',
'index.php?post_type=product&name=$matches[1]&sku=$matches[2]',
'top'
);
flush_rewrite_rules();
}
Я новичок в продвинутом кодировании WordPress, буду очень признателен за любые рекомендации и помощь.
Функцию custom_product_permalink()
можно изменить, чтобы найти и включить полный ярлык категории (с родительскими ярлыками) и исключить строку «продукт» (что также меняет правило перезаписи):
add_filter('post_type_link', 'custom_product_permalink', 1, 2);
function custom_product_permalink($link, $post) {
if ($post->post_type == 'product') {
$cat_tax = 'product_cat';
// Find the product category IDs
$cat_ids = wp_get_post_terms($post->ID, $cat_tax, ['fields' => 'ids']);
$cat_full_slug = '';
if (is_array($cat_ids) && !empty($cat_ids)) {
// Build a full hierarchical category slug
$cat_full_slug = get_term_parents_list($cat_ids[0], $cat_tax, [
'format' => 'slug',
'separator' => '/',
'link' => false,
'inclusive' =>true
]);
}
// Convert the entire URL to lowercase
return strtolower(home_url('shop/' . $cat_full_slug .
$post->post_name . '-' .
get_post_meta($post->ID, '_sku', true) . '/'));
} else {
return $link;
}
}
add_action('init', 'custom_product_permalink_rewrite_rules');
function custom_product_permalink_rewrite_rules() {
add_rewrite_rule(
'shop/.+/([^/]+)-([^/]+)/?$',
'index.php?post_type=product&name=$matches[1]&sku=$matches[2]',
'top'
);
flush_rewrite_rules();
}
Обратите внимание, что для этого у продукта должна быть хотя бы одна категория. В случаях, когда существует несколько категорий, используется только первая, возвращаемая wp_get_post_terms()
. _sku
также является обязательным и не может содержать -
.