Last active
December 8, 2018 18:58
-
-
Save webmandesign/29c25b036179816a25b26a6fba418ee2 to your computer and use it in GitHub Desktop.
Can we use `locate_template()` for other than "Template files"?
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* We need to load this file only if it exists: | |
* - first checking in child theme, | |
* - then trying parent theme. | |
*/ | |
$file_path_relative = 'assets/css/for-processing.css'; | |
/** | |
* If we could use `locate_template()` function for any file | |
* (and not just for "Template files") in WordPress themes, | |
* our job is much easier: a single line of code. | |
* | |
* @link https://developer.wordpress.org/reference/functions/locate_template/ | |
* @link https://developer.wordpress.org/themes/basics/template-files/ | |
*/ | |
locate_template( $file_path_relative, true, false ); | |
// ...OR... | |
/** | |
* On the other hand, if `locate_template()` file should be used | |
* for "Template files" only, we are stuck with this code instead: | |
*/ | |
$file_path_absolute = array( | |
'in_child_theme' => trailingslashit( get_stylesheet_directory() ) . $file_path_relative, | |
'parent_theme_fallback' => trailingslashit( get_template_directory() ) . $file_path_relative, | |
); | |
if ( file_exists( $file_path_absolute['in_child_theme'] ) ) { | |
require $file_path_absolute['in_child_theme']; | |
} elseif ( file_path_absolute_exists( $file_path_absolute['parent_theme_fallback'] ) ) { | |
require $file_path_absolute['parent_theme_fallback']; | |
} | |
// ...OR... | |
/** | |
* We could actually optimize more: | |
*/ | |
$file_path_absolute = get_theme_file_path( $file_path_relative ); | |
if ( file_exists( $file_path_absolute ) ) { | |
require $file_path_absolute; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Alternative solution is using a dedicated file loading/locating PHP class in your WordPress theme.