0

I'm adding custom URLs in Wordpress using add_rewrite_rule. Following is my code:-

add_action( 'init', 'some_function' );
function some_function(){
    global $wp_rewrite; 
    add_rewrite_rule(  // This is not working.
        '([a-zA-Z0-9-]+)/dp/([a-zA-Z0-9-]+)/?$',
        'index.php?partners_deal_url=$matches[1]',
        'top' );
    add_rewrite_rule(  // This is working.
        'dp/([a-zA-Z0-9-]+)/?$',
        'index.php?partners_deal_url=$matches[1]',
        'top' );
    $wp_rewrite->flush_rules();
}

add_filter( 'query_vars', 'wpse26388_query_vars' );
function wpse26388_query_vars( $query_vars ){
    $query_vars[] = 'partners_deal_url';
    return $query_vars;
}

add_action( 'template_redirect', 'prefix_url_rewrite_templates' );
function prefix_url_rewrite_templates() {
    if (get_query_var('partners_deal_url')){
        add_filter( 'template_include', function() {
            return get_template_directory() . '/single-deal.php';
        });
    }
}

However, some of my custom URLs are working, and some are not. Not sure, why?

The below URL is not working:-

add_rewrite_rule('([a-zA-Z0-9-]+)/dp/([a-zA-Z0-9-]+)/?$',
        'index.php?partners_deal_url=$matches[1]', 'top' );

For eg:- When I browse to domain.com/ABCD/dp/PQR, it says 404 not found.

The below rule is working fine.

add_rewrite_rule('dp/([a-zA-Z0-9-]+)/?$',
            'index.php?partners_deal_url=$matches[1]', 'top' );

For eg:- When I browse to domain.com/dp/PQR, it works perfectly fine.

However, the below URL is not working:-

add_rewrite_rule('([a-zA-Z0-9-]+)/dp/([a-zA-Z0-9-]+)/?$',
        'index.php?partners_deal_url=$matches[1]', 'top' );

For eg:- When I browse to domain.com/ABCD/dp/PQR, it says 404 not found.

I tested my url rules using Monkeyman Rewrite Analyzer, and URL pattern is matched, but it still gives 404 error.

What exactly am I missing?

  • If you inspect $wp_query in the template, you'll see what WordPress is trying to query for in each case. – Milo Dec 27 '18 at 17:55

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.