In order to achieve this URL-level content display in WordPress without using internal functions that depend on the $post
variable or get_post
, we can make use of the template_redirect
action along with URL rewriting.
- Add Rewrite Rules.
- Handle the Redirect.
Here’s an example of how to implement this:
// Here we have added rewrite rules.
function custom_rewrite_rules() {
add_rewrite_rule( '^url-1/?$', 'index.php?pagename=url-2', 'top' );
}
add_action( 'init', 'custom_rewrite_rules' );
// This is to Serve content of url-2 when accessing url-1.
function load_template_for_url_1( $template ) {
if ( is_page( 'url-1' ) ) {
// Here we are getting the template for url-2.
$new_template = locate_template( 'page-url-2.php' ); // We need to adjust based on your template file.
if ( $new_template ) {
return $new_template;
}
}
return $template;
}
add_filter( 'template_include', 'load_template_for_url_1' );
// This is to flush rewrite rules on activation
function flush_rewrite_on_activation() {
custom_rewrite_rules();
flush_rewrite_rules();
}
register_activation_hook( __FILE__ , 'flush_rewrite_on_activation' );
Once we have done the above steps we need to replace url-1 and url-2 with the actual slugs of your posts. After adding this code, we may need to visit the WordPress Settings > Permalinks
page to flush the rewrite rules manually. After this we need to ensure that your caching plugin is configured to allow for this type of redirection.