Change Page Template Based on URL Rewrite in WordPress

Change Page Template Based on URL Rewrite in 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 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 URL structure. After appending these endpoints, the new URL structure would be news/{news-event}/photos and news/videos.

Custom URL

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 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

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

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.

WPblog

WP Blog is dedicated to getting you up and running
in the field of Wp blog wizardry - No Wands Involved!