Ace Goulet

Custom Rewrites For Static Pages

Sometimes in the course of a WordPress theme build there is a need to have a pretty url for a page that you don’t necessarily want to exist in the CMS. For example, if you create a php file for a custom json feed or some kind of API endpoint, etc. As long as your custom file includes the wp-blog-header.php file (to initializeWordPress), you can target it with WordPress’ rewrite rules.

This is a better route to take than building a page template and creating a page in the WP admin, as clients could then potentially delete that page and break whatever functionality was dependent on this page.

So in this example I’m taking the url and simplifying it into

function json_rewrite() {
add_action('init', 'json_rewrite', 10, 0);

Important note: WordPress has a bug that it’s had for 6+ years where rewrites of this kind serve the right content, but 404 headers…which obviously is bad for API endpoints and such. However, there is a simple solution. In the php file you are rewriting to, make sure to include the wp-blog-header.php (this initializes WP and all the goodies that come along with it…it is located at the root of your wordpress install, so you’ll need to route to that relative to your php file) and then include the simple wp function status_header(200). This will force the content delivered to have a status of 200 instead of 404.

 /** Loads the WordPress Environment and Template */
 require( '../../../wp-blog-header.php' );
 status_header( 200 );
 Page Content Here!

Additional Note: WordPress does not like camelcasing in your rewrites, so don’t do it (you typically wouldn’t want to anyway because SEO and because BROWSERS and because camel joe is kind of a dick).

Exit mobile version