0

I am in need of some advice. I have a section on my home page dynamically pulling in a list of terms from a custom table in the WP db. I have made a unique custom URL for each of these terms based on test code:

<a href="<?php bloginfo('url'); ?>/test-directory/test-code/<?php echo $record->test_code; ?>">

This works fine. My next step is to have these URLs, when clicked, load the accompanying dynamic content into a template. I tried the code below to create rewrite rules to point to a template but it just isn't working. It doesn't load the template but the default blog template. I am using a child theme but this should work:

function my_add_query_vars( $qvars ) {
    $qvars[] = 'test-directory';
        $qvars[] = 'test-code';
        return $qvars;
}

add_action('query_vars', 'my_add_query_vars');


function my_add_rewrite_rules( $wp_rewrite ) {
    $newrules = array();
    $new_rules['^test-directory/(.*)/(.*)'] = 'index.php?test-directory=$matches[1]test-code=$matches[2]';
    $wp_rewrite->rules = $new_rules + $wp_rewrite->rules;
}

add_action('generate_rewrite_rules', 'my_add_rewrite_rules');

function my_template_redirect() {
    if( get_query_var('test-code') ) {
        include_once(locate_template('template-faq-fullwidth.php', true));
        exit();
    }
}

add_action('template_redirect','template_redirect');

Any help is appreciated as always.Thanks.

1 Answer 1

1

Firstly, don't forget to always flush your rewrite rules by going to Settings -> Permalinks and just clicking on Save Changes

Now on your problem, it seems that you're missing an '&' in your query:

$new_rules['^test-directory/(.*)/(.*)'] = 'index.php?test-directory=$matches[1]&test-code=$matches[2]';

Notice the & after $matches[1]

On the other hand, your 'template_redirect' action is not calling the correct function (template_redirect instead of my_template_redirect)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.