I am adding a rewrite rule to a PHP script included in a WordPress page with the permalink kb
So I can access domain.com/kb and display the page.
function wdm_add_rewrite_rules() { add_rewrite_rule( '^kb/([^/]+)/?$', 'kb?kb_cat=$matches[1]&kb_seq=1', 'top'); } add_action('init', 'wdm_add_rewrite_rules');
But when I visit a page that contains other strings in the URL, I get a 404.
So when I visit domain.com/kb it shows the correct page, then when I visit domain.com/kb/84/92 it shows 404
I just need to be able to read the additional url parameters in the PHP script, like $_GET["kb_cat"]
P粉9491909722024-01-17 11:01:28
Try this:
function wdm_add_rewrite_rules() { add_rewrite_rule( '^kb\/([^\/]+)\/?([^\/]+)$', 'kb?kb_cat=$matches[1]&kb_seq=1', 'top'); } add_action('init', 'wdm_add_rewrite_rules');
You can check the regular expression at https://regex101.com/ or any other similar online website for the contest
P粉1059715142024-01-17 00:28:54
function wdm_add_rewrite_rules() { add_rewrite_rule( '^kb$', 'index.php?kb_cat=$matches[1]&kb_seq=1', 'top'); } add_action('init', 'wdm_add_rewrite_rules');
Go one step further and use parameters:
function add_query_vars_filter( $vars ){ $vars[] = "kb_cat"; $vars[] = "kb_seq"; return $vars; } add_filter( 'query_vars', 'add_query_vars_filter' );
Then load the custom template file:
function include_custom_template($template){ if(get_query_var('kb_cat') && get_query_var('kb_seq')){ $template = get_template_directory() ."/my-custom-template.php"; } return $template; } add_filter('template_include', 'include_custom_template');
Once added to functions.php
, go to Settings > Permalinks and click Save Changes to reset refresh rules