Skip to content

Instantly share code, notes, and snippets.

@derpixler
Last active August 29, 2015 14:16
Show Gist options
  • Save derpixler/0fe88879e4c2338aab93 to your computer and use it in GitHub Desktop.
Save derpixler/0fe88879e4c2338aab93 to your computer and use it in GitHub Desktop.
Simple WordPress Template-API
/**
* Add some rewrite rules
*
* @return void
*/
function tplapi_add_rewrite_rule(){
add_rewrite_rule( '^tplapi/(.*?)/?$','index.php?tplapi=$matches[1]', 'top' );
}
add_action( 'init', 'tplapi_add_rewrite_rule', 0 );
/**
* Add some query vars
*
* @return void
*/
function tplapi_add_query_vars( $qvars ) {
$qvars[] = 'tplapi';
return $qvars;
}
add_filter( 'query_vars', 'tplapi_add_query_vars', 10, 1 );
/**
* Load custom template
*
* @author r.reimann <info@rene-reimann.de>
* @param
*/
function tplapi_load_template( $default_tpl_path ){
global $wp_query;
if( array_key_exists( 'tplapi', $wp_query->query ) ){
$tpl = $wp_query->query['tplapi'];
$tpl_path = str_replace( basename( $default_tpl_path ), $tpl.'.php', $default_tpl_path );
if( file_exists( $tpl_path ) )
return $tpl_path;
}
return $default_tpl_path;
}
add_filter( 'template_include', 'tplapi_load_template', 99 );
/**
* Validat the last Modifikation of this File
* on modification flush the rewrite rules
*
* @author r.reimann <info@rene-reimann.de>
* @return void
*/
function tplapi_flush_rules() {
$o = '__UNIQUEKEY__';
$v = filemtime( __FILE__ );
$d = array( 'version' => 0, 'time' => time() );
$r = wp_parse_args( get_option( $o, array() ), $d );
if ( $r['version'] != $v ) {
flush_rewrite_rules();
$a = array( 'version' => $v, 'time' => time() );
if ( ! update_option( $o , $a ) )
add_option( $o , $a );
}
}
add_action( 'init', 'tplapi_flush_rules' );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment