php - WooCommerce 类别和子类别的永久链接
问题描述
我在stackexchanges上找到了这个解决方案来设置这样的永久链接结构
Product 1: /shop/category/subcategory/product1/
Product 2: /shop/category/product2/
到目前为止,在 function.php 中使用此代码的解决方案适用于产品和子类别,它们现在都有基本 URL“shop”。但是父类别现在显示的是 404 页面。
function wpse_291143_generate_taxonomy_rewrite_rules( $wp_rewrite ) {
global $wp_rewrite;
$base = "shop";
$rules = array();
$terms = get_terms( array( 'taxonomy' => 'product_cat', 'hide_empty' => false ));
foreach($terms as $term) {
$term_children = get_terms( array(
'taxonomy' => 'product_cat',
'parent' => intval($term->term_id),
'hide_empty' => false
)
);
if($term_children) {
foreach ( $term_children as $term_child ) {
$rules[$base . '/' . $term->slug . '/' . $term_child->slug . '/?$'] = 'index.php?product_cat=' . $term_child->slug;
}
}
}
$wp_rewrite->rules = $rules + $wp_rewrite->rules;
return $wp_rewrite->rules;
}
add_action('generate_rewrite_rules', 'wpse_291143_generate_taxonomy_rewrite_rules');
我怎样才能让这个代码工作,它也适用于父类别?
类别基础:商店
自定义基础网址/shop/%product_cat%/
解决方案
遇到同样的问题终于在这里找到了解决方案: https ://wordpress.org/support/topic/same-permalink-for-shop-category-custom-base-with-child-cats/
add_filter( 'rewrite_rules_array', function( $rules ) {
$new_rules = array();
$terms = get_terms( array(
'taxonomy' => 'product_cat',
'post_type' => 'product',
'hide_empty' => false,
));
if ( $terms && ! is_wp_error( $terms ) ) {
$siteurl = esc_url( home_url( '/' ) );
foreach ( $terms as $term ) {
$term_slug = $term->slug;
$baseterm = str_replace( $siteurl, '', get_term_link( $term->term_id, 'product_cat' ) );
// rules for a specific category
$new_rules[$baseterm .'?$'] = 'index.php?product_cat=' . $term_slug;
// rules for a category pagination
$new_rules[$baseterm . '/page/([0-9]{1,})/?$' ] = 'index.php?product_cat=' . $term_slug . '&paged=$matches[1]';
$new_rules[$baseterm.'(?:feed/)?(feed|rdf|rss|rss2|atom)/?$'] = 'index.php?product_cat=' . $term_slug . '&feed=$matches[1]';
}
}
return $new_rules + $rules;
} );
/**
* Flush rewrite rules when create new term
* need for a new product category rewrite rules
*/
function imp_create_term() {
flush_rewrite_rules(false);;
}
add_action( 'create_term', 'imp_create_term' );
推荐阅读
- r - 如果它们具有相同的列,则合并 tibble 表的列表
- angularjs - 如何在打字稿中触发离子后退按钮
- javascript - 使用 AvField[type=date] 将时间戳解析为日期
- ios - uinavigationbar ios中标题的上边距问题
- bluetooth - 蓝牙广告数据
- javascript - 禁用JavaScript时的CSS媒体查询?
- r - `use_import_from' 不是从 'namespace:usethis` 导出的对象
- python - 如何在 PyCharm 中将实例属性转换为类属性
- highcharts - HighCharts:如何在具有 2 个系列的图表中使用 pointRange?
- angular - 定义可观察的接口