How To Create Custom Urls In WordPress With Add_Rewrite_Rule
Rewrite rules map a pretty URL, like /deals/summer-sale/, to a query that WordPress understands. Use them when you need URLs that do not belong to a normal page, post or taxonomy.
Step 1: add the rule and a query variable
function lotgrafix_rewrite_rules() {
add_rewrite_rule(
'^deals/([^/]+)/?$',
'index.php?lotgrafix_deal=$matches[1]',
'top'
);
}
add_action( 'init', 'lotgrafix_rewrite_rules' );
function lotgrafix_query_vars( $vars ) {
$vars[] = 'lotgrafix_deal';
return $vars;
}
add_filter( 'query_vars', 'lotgrafix_query_vars' );
Step 2: load your own template
function lotgrafix_deal_template( $template ) {
$lotgrafix_deal = get_query_var( 'lotgrafix_deal' );
if ( $lotgrafix_deal ) {
$custom = get_template_directory() . '/lotgrafix-deal.php';
if ( file_exists( $custom ) ) {
return $custom;
}
}
return $template;
}
add_filter( 'template_include', 'lotgrafix_deal_template' );
Step 3: use the value in the template
<?php
$lotgrafix_slug = sanitize_title( get_query_var( 'lotgrafix_deal' ) );
get_header();
?>
<h1><?php echo esc_html( $lotgrafix_slug ); ?></h1>
<?php get_footer(); ?>
Flush the rules once
WordPress caches rewrite rules. After adding a rule, go to Settings, Permalinks and click Save Changes. In a plugin, flush only on activation.
function lotgrafix_activate() {
lotgrafix_rewrite_rules();
flush_rewrite_rules();
}
register_activation_hook( __FILE__, 'lotgrafix_activate' );
Warning
Never call flush_rewrite_rules() on init or on every page load. It is an expensive operation that rebuilds the rules and writes to the database.
Rule with several parts
add_rewrite_rule(
'^reports/([0-9]{4})/([^/]+)/?$',
'index.php?lotgrafix_year=$matches[1]&lotgrafix_report=$matches[2]',
'top'
);
Remember to register both lotgrafix_year and lotgrafix_report as query variables.


