URL rewrite rule

时间:2019-03-19 作者:Alexy

我有分类学product_brandproduct_cat

我有一个链接:

/product_brand/brand_name/?attributes[product_cat]=product_cat_id
如何转换为漂亮的url?

/product_brand/brand_name/product_cat_name

  function custom_rewrite_rules() {
        add_rewrite_rule(\'^product_brand/(.*)/(.*)?\', \'index.php?&attributes[product_cat]=$matches[1]\', \'top\');
  }
    add_action(\'init\', \'custom_rewrite_rules\');

1 个回复
最合适的回答,由SO网友:Alexy 整理而成

    function custom_rewrite_rules() {
            add_rewrite_rule( \'^product_brand/([^/]+)/page/([0-9]{1,})/?\', \'index.php?product_brand=$matches[1]&page=$matches[2]\', \'top\' );
            add_rewrite_rule( \'^product_brand/([^/]+)/([^/]+)/page/([0-9]{1,})/?\', \'index.php?product_brand=$matches[1]&product_cat=$matches[2]&page=$matches[3]\', \'top\' );
            add_rewrite_rule(\'^product_brand/([^/]+)/([^/]+)?\', \'index.php?product_brand=$matches[1]&product_cat=$matches[2]\', \'top\');

            add_filter( \'query_vars\', function( $vars ){
                $vars[] = \'product_brand\';
                $vars[] = \'product_cat\';
                return $vars;
            } );
     }
     add_action(\'init\', \'custom_rewrite_rules\');
和分页

add_action( \'pre_get_posts\', function() {
 $page = get_query_var(\'page\');
 $query->set( \'paged\', $page );
 return $query;
} );