PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Saturday, February 5, 2022

[FIXED] Can't rewrite product variation URL using add_rewrite_rule in WordPress

 February 05, 2022     woocommerce, wordpress, wordpress-theming     No comments   

Issue

I have an issue, I need to rewrite the variation slug for products in WooCommerce. For example, I have this URL:

http://localhost:8888/wordpress/product/wordpress-pennant/?attribute_pa_color=blue

What I need is this one:

http://localhost:8888/wordpress/product/wordpress-pennant/blue

I tried this code, but it doesn't work:

add_action( 'init', 'add_rewrite_rules' );
function add_rewrite_rules() {
    add_rewrite_rule(
        '^product/([^/]*)?',
        'index.php?product=$matches[1]&attribute_pa_color=$matches[2]',
        'top'
    );
    add_rewrite_tag('%attribute_pa_color%', '([^&]+)');
}

I can't understand what I'm doing wrong, I also made flush for permalinks.


Solution

I find out that I have mistakes in my code, so finally it should be like this:

add_action( 'init', 'add_rewrite_rules' );
function add_rewrite_rules() {
    add_rewrite_rule('^product/(.+?)/(.+?)/?$', 'index.php?product=$matches[1]&attribute_pa_color=$matches[2]', 'top');
    add_rewrite_tag('%attribute_pa_color%', '([a-zA-Z0-9-]+)');
}


Answered By - Nas
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing