Home  >  Q&A  >  body text

WordPress rewrite rule setup guide

How to set up rewrite rules in WordPress to handle the following URL: "https://mywebsite.com/product-detail/model=MH-TOOL-152&isToolId=1" This is the scan QR code The redirect link after. I should get the value of the parameter model as this is the base of the product SKU and put my shortcode under the product details page.

I tried this below and it redirected me to the homepage. I'm trying to set it up to only show on product detail pages.

function mywebsite_rewrite_rule() {
   add_rewrite_rule('^product-detail/([^/]*)/?', 'index.php/model=$matches[1]', 'top');
}
add_action('init', 'mywebsite_rewrite_rule', 10, 0);

P粉496886646P粉496886646257 days ago384

reply all(1)I'll reply

  • P粉321584263

    P粉3215842632024-01-11 09:29:05

    I've figured out how to use rewrite rules in WP. This is what I've been doing.

    //获取model变量
    add_filter('query_vars', 'add_model_var_prodDetail', 10, 1);
    function add_model_var_prodDetail($vars_sku){
        $vars_sku[] = 'model';
        return $vars_sku;
    }
    
    //在特定页面product-detail上重写URL
    add_action('init', 'rewrite_rule_productDetail', 10, 0);
    function rewrite_rule_productDetail() {
        add_rewrite_rule('^product-detail/([^/]*)/?','index.php?post_type=page&pagename=product-detail&model=$matches[1]','top');
        add_rewrite_tag( '%model%', '(.+)' );
    }

    Then use get_query_var to retrieve the model

    reply
    0
  • Cancelreply