Skip to content

Instantly share code, notes, and snippets.

@illucent
Forked from kovshenin/static-templates.php
Created February 21, 2014 10:00

Revisions

  1. @kovshenin kovshenin revised this gist Feb 21, 2014. 1 changed file with 3 additions and 3 deletions.
    6 changes: 3 additions & 3 deletions static-templates.php
    Original file line number Diff line number Diff line change
    @@ -8,9 +8,9 @@
    *
    * Examples:
    *
    * - /foo/ => /wp-content/themes/static-templates/foo.php
    * - /foo/bar/ => /wp-content/themes/static/templates/foo-bar.php
    * - /foo/bar/baz/ => /wp-content/themes/static/templates/foo-bar-baz.php
    * - /foo/ => /wp-content/themes/twentyten/static-templates/foo.php
    * - /foo/bar/ => /wp-content/themes/twentyten/static/templates/foo-bar.php
    * - /foo/bar/baz/ => /wp-content/themes/twentyten/static/templates/foo-bar-baz.php
    *
    * You're welcome.
    */
  2. @kovshenin kovshenin created this gist Feb 21, 2014.
    49 changes: 49 additions & 0 deletions static-templates.php
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,49 @@
    <?php
    /**
    * Plugin Name: Static Templates
    *
    * If most of your site content is in .php template files, and you're tired of
    * creating new pages, assigning them page templates, creating page templates
    * then doing it all over again on production, this plugin is for you.
    *
    * Examples:
    *
    * - /foo/ => /wp-content/themes/static-templates/foo.php
    * - /foo/bar/ => /wp-content/themes/static/templates/foo-bar.php
    * - /foo/bar/baz/ => /wp-content/themes/static/templates/foo-bar-baz.php
    *
    * You're welcome.
    */

    add_filter( 'template_include', function( $template ) {
    $request = trim( $_SERVER['REQUEST_URI'], '/' );
    if ( ! is_404() || empty( $request ) )
    return $template;

    // Loop throuh parts and makes ure they're sane.
    $parts = explode( '/', trim( $request, '/' ) );
    foreach ( $parts as $part )
    if ( ! preg_match( '#^[a-z0-9-]+$#i', $part ) )
    return $template;

    // Using stylesheet directory so parent/child themes don't share static pages.
    $template_name = implode( '-', $parts );
    $template_path = get_stylesheet_directory() . sprintf( '/static-templates/%s.php', $template_name );

    if ( file_exists( $template_path ) ) {
    $template = $template_path;

    // We want trailing slashes, this is our last chance for a redirect.
    if ( trailingslashit( $_SERVER['REQUEST_URI'] ) != $_SERVER['REQUEST_URI'] ) {
    wp_safe_redirect( trailingslashit( $request ) );
    die();
    }
    }

    return $template;
    });

    add_action( 'template_redirect', function() {
    // Core will redirect /dashboard/ to /wp-admin/, we don't want that. Unless you do.
    remove_action( 'template_redirect', 'wp_redirect_admin_locations', 1000 );
    });