Search code examples
wordpress.htaccessurl-rewritingpermalinks

Wordpress add_rewrite_rule gives 404


I want to change the permalink structure for specific custom post type.i.e

http://test.com/brand/calvin-klien?mtype=tab2
                     ^this is dynamic    

To

http://test.com/brand/calvin-klien/mtype/tab2
                      ^this is dynamic

Here is a piece of code I tried.

Registering add_rewrite_tag

function custom_rewrite_tag() {
        add_rewrite_tag('%mtype%', '([a-z0-9\-]+)');
    }
    add_action('init', 'custom_rewrite_tag', 10, 0);

add_action('init', 'wpse50530_journal_archive_rewrite', 10, 0);

Code1

function wpse50530_journal_archive_rewrite(){

   add_rewrite_rule('brand/([a-z0-9\-]+)/([a-z0-9\-]+)/$','index.php?name=$matches[1]/?mtype=$matches[2]','top');
}

Code2

add_action('generate_rewrite_rules', 'work_list');
function work_list($wp_rewrite) {
    $newrules = array();
    $newrules['brand/([a-z0-9\-]+)/([a-z0-9\-]+)/$'] = 'index.php?name=$matches[1]&mtype=$matches[2]';
    $wp_rewrite->rules = $newrules + $wp_rewrite->rules;

I have tried both above codes, flushed permalinks but still a 404. I dont know why it is creating $matches in htaccess as htacces doesnt know WHAT IS $matches

Also I have tried monkeyman-rewrite-analyzer plugin which is showing the correct matched result for my permalink but still word press showing 404. See attached screenshots for Code1 & Code2

Code1![][1]Code2


Solution

  • The following code should help

    add_action( 'init', 'so_27487849' );
    
    function so_27487849() {
    
        add_rewrite_rule(
            '^brand/([^/]*)/mtype/([^/]*)/?',
            'index.php?name=$matches[1]&mtype=$matches[2]',
            'top');
    
    }
    

    Flush your permalinks and it should work.