Skip to content

Inserting custom variables and rewriting urls in WordPress

Warning: this article was written over 12 years ago, some information may be out of date.

Pretty permalinks are one of the most welcome features of WordPress. Interesting, you can also use them when you need to use custom variables for a plugin, for instance.
In my case, I had to hook up, for the content of the page, to an external SOAP-like service, to which I had to send precise parameters.
The solution to this problem is quite simple: permalinks must be rewritten for the pages where those parameters are to be used.
For convenience, I have used the file name of the page template to intercept the page slugs.
First of all, since the function does not need to be called up in the administration, all the code must be entered in a condition:

if (!is_admin()) {

Then the WordPress rewrite rules cache must be cleared (this part of the code is indispensable but should be used sparingly)

function wporg_flush_rules(){
global $wp_rewrite;
$wp_rewrite->flush_rules();
}
add_filter('init','wporg_flush_rules');

Variables must then be added among those managed by WordPress. In this case, I am adding two:

function wporg_add_query_vars($aVars) {
    $aVars[) = "var-one";
    $aVars[) = "var-two";
    return $aVars;
}
add_filter('query_vars', 'wporg_add_query_vars');

Finally, we intercept those pages that have precise page templates (always two) and assign the new rewrite rules:

function wporg_add_rewrite_rules($rules) {

$specialpages = query_posts(array(
'post_type' => 'page',
'posts_per_page' => -1,
'meta_query' => array(
'relation' => 'OR',

array(
'value' => 'template-one.php',
),
array(
'value' => 'template-two.php',
)
)
) );

foreach($specialpages as $post) :
setup_postdata($post);

$slug= $post->post_name;

$new_rules = array(''.$slug.'/([^/)+)/([^/)+)/?$' => 'index.php?pagename='.$slug.'&var-one=$matches[1)&var-two=$matches[2)');
//This second rule allows to preserve pagination
$new_rules_1 = array(''.$slug.'/([^/)+)/([^/)+)/page/([^/)+)/?$' => 'index.php?pagename='.$slug.'&var-one=$matches[1)&var-two=$matches[2)&paged=$matches[3)');

$rules = $new_rules + $new_rules_1 + $rules;

endforeach;
wp_reset_query();
return $rules;
}

add_filter('rewrite_rules_array', 'wporg_add_rewrite_rules');

}

The result is that if you assign template-one.php or template-two.php to a page, you can use the query https://my_site_url/page/var-one=value-one&var-two=value-two and the URL will be rewritten as https://my_site_url/page/value-one/value-two/.

Previous article

Next article

Thread

Leave a comment

Your email address will not be published.