permalinks – Add additional URL variations for a Post
My goal is to have multiple variations of the same URL resolve to the same Post. The Post itself would have some different treatments based on the URL the reader followed to get there.
In searching here I’ve found many cases of changing the URL but few applicable to adding more variations to an existing URL structure.
Lets say that the current URL structure for a regular Post follows this structure:
/{year}/{slug}/
/2022/hello-world/
I’m trying to modify it so that these variations could all resolve to the same Post:
/{year}/{slug}/
/{year}/{slug}/{param1}/
/{year}/{slug}/{param2}/
/{year}/{slug}/{param3}/
And where a value like param1
was given, it would be detectable so I could modify things like the Page Title, META descriptions, and content itself. For that I was planning to rely on various hooks.
My current attempts are variations of this code:
function modify_content( $content ) {
global $wp_query;
if (isset( $wp_query->query_vars['example_param'] )) {
$content="<h2>Test: " . $wp_query->query_vars['example_param'] . '</h2>' . $content;
}
return $content;
}
add_filter( 'the_content', 'modify_content', 1 );
function add_param_query_vars( $qvars ) {
$qvars[] = 'example_param';
return $qvars;
}
add_filter( 'query_vars', 'add_param_query_vars' );
add_rewrite_rule('^([0-9]{4})/(.*)/(.*)/?$', 'index.php?post_lang=$example_param[3]', 'top');
I’ve not been able to get the value for example_param. I’ve managed in some cases to get hit the Post URL with parameters at end without getting 404, but it doesn’t seem reliable and often just redirects to an archive page or front-page.
Leave an answer