Change Page Template Based on URL Rewrite in WordPress
WordPress URL rewriting is a common WordPress practice where the contents (to be displayed) are changed.
Let me explain. Normally, when you type a URL, the server goes to that location and serves whatever files it founds there. In the case of WordPress URL rewriting, the URL remains the same but the server goes to the rewritten URL to look for the content.
This article will show you how to:
- Add a rewrite rule for a custom post type permalink in WordPress
- Use a page template based on the rewrite rule
Consider the following news post type. The permalink used for this type is news/{news-event}.
Now I would like to add two separate endpoints, photos and videos to this WordPRess URL structure. After appending these endpoints, the new URL structure would be news/{news-event}/photos and news/videos.
Custom URL
1 2 3 4 5 6 |
function prefix_news_rewrite_rule() { add_rewrite_rule( 'news/([^/]+)/photos', 'index.php?news=$matches[1]&photos=yes', 'top' ); add_rewrite_rule( 'movie/([^/]+)/videos', 'index.php?news=$matches[1]&videos=yes', 'top' ); } add_action( 'init', 'prefix_news_rewrite_rule' ); |
By using the add_rewrite_rule function, I have added two custom rewrite rules to the base URL. At the same time, I have
set two query variables to the WordPress URL. Notice that I have avoided the add_rewrite_endpoint function because I do not want to add the endpoint to every permalink on the website.
Register Query Vars
1 2 3 4 5 6 7 |
function prefix_register_query_var( $vars ) { $vars[] = 'photos'; $vars[] = 'videos'; return $vars; } add_filter( 'query_vars', 'prefix_register_query_var' ); |
I have added these query variable to WordPress. I could now easily use them in custom code. Now notice that if I go to the URL news/{news-event}/photos, the browser’s address bar will still show either single-news.php or single.php
Set the Template
1 2 3 4 5 6 7 8 9 10 11 12 13 |
function prefix_url_rewrite_templates() { if ( get_query_var( 'photos' ) && is_singular( 'news' ) ) { add_filter( 'template_include', function() { return get_template_directory() . '/single-news-image.php'; }); } if ( get_query_var( 'videos' ) && is_singular( 'news' ) ) { add_filter( 'template_include', function() { return get_template_directory() . '/single-news-video.php'; }); } } add_action( 'template_redirect', 'prefix_url_rewrite_templates' ); |
Now in this snippet, I have set the condition that if there is a query variable, photos or videos and it is a single news page, set the template as single-news-image.php and single-news-event.php (depending upon the query variable)
Conclusion
In this tutorial, I have discussed custom page template based on URL rewrite in WordPress. If you need any help in understanding the idea or would like to contribute an alternate solution to the problem, do leave a comment below.
Create Faster WordPress Websites!
Free eBook on WordPress Performance right in your inbox.