WordPress Managed Hosting - 40% Off For 4 Months - Coupon Code: BFCM2021 Avail Now

Change Page Template Based on URL Rewrite in WordPress

Moeez — July 6, 2017 2 Minutes Read
wordpress site url

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

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

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)


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.

    Create Faster WordPress Websites!

    Free eBook on WordPress Performance right in your inbox.

      Moeez is ‘The’ blogger in charge of WPblog. He loves to interact and learn about WordPress with people in the WordPress community. Outside his work life, Moeez spends time hanging out with his friends, playing Xbox and watching football on the weekends. You can get in touch with him at moeez[at]wpblog.com.



        WordPress Help Zone - Ultimate WordPress Pit-Stop

        Learning WordPress? Or are you expert enough to help others? Join our WP Facebook group!