Skip to content

Instantly share code, notes, and snippets.

@lkraav
Created June 28, 2015 10:29
Show Gist options
  • Save lkraav/4e44cadc6131f2bfa4d1 to your computer and use it in GitHub Desktop.
Save lkraav/4e44cadc6131f2bfa4d1 to your computer and use it in GitHub Desktop.
hybrid_locate_template() as discussed in https://github.com/justintadlock/hybrid-core/issues/111
<?php
/*
Plugin Name: Hybrid Core hybrid_locate_template()
Plugin URI: https://github.com/justintadlock/hybrid-core/issues/111
Description: Free yourself from TEMPLATEPATH and STYLESHEETPATH constants
Author: Leho Kraav
Author URI: http://conversionready.com
Version: 2015.06.10
License: MIT
*/
if ( defined( "DOING_AJAX" ) && DOING_AJAX ) {
return;
}
if ( is_admin() ) {
return;
}
# TODO what's the hybrid standard priority for "always last"?
# TODO has to be module-level opt-in for now, overrides existing filters too aggressively
# add_filter( "hybrid_content_template", "hybrid_content_template", 15, 2 );
/**
* Because plugins need to host their own templates, but locate_template()
* forces theme-only hierarchy.
*
* wp_templating_constants() runs very early, after "setup_theme" action.
* Plugins may not able to determine request responsibility until much later.
*
* By that time templating constants are set and you're screwed.
*
* http://chat.stackexchange.com/transcript/message/22088394#22088394
* https://developer.wordpress.org/reference/functions/locate_template/
* https://github.com/justintadlock/hybrid-core/issues/111
* https://core.trac.wordpress.org/ticket/13239
* https://core.trac.wordpress.org/ticket/14310
* https://core.trac.wordpress.org/ticket/22355
* https://github.com/GaryJones/Gamajo-Template-Loader/blob/develop/class-gamajo-template-loader.php#L141
*/
function hybrid_locate_template( $template_names, $load = false, $require_once = true ) {
$located = '';
$stylesheetpath = get_stylesheet_directory();
$templatepath = get_template_directory();
foreach ( (array) $template_names as $template_name ) {
if ( ! $template_name ) {
continue;
}
# TODO such non-DRY core code, optimize
if ( file_exists( $stylesheetpath . '/' . $template_name ) ) {
$located = $stylesheetpath . '/' . $template_name;
break;
} elseif ( file_exists( $templatepath . '/' . $template_name ) ) {
$located = $templatepath . '/' . $template_name;
break;
}
}
if ( $load && "" !== $located ) {
load_template( $located, $require_once );
}
return $located;
}
/**
* Overrides locate_template() result with hybrid_locate_template()
*/
function hybrid_content_template( $template_name, $templates ) {
$template_name = hybrid_locate_template( $templates, false, false );
return $template_name;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment