Skip to content

Instantly share code, notes, and snippets.

@webmandesign
Last active December 8, 2018 19:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save webmandesign/8578ca85da784bdcff9730deab548b1f to your computer and use it in GitHub Desktop.
Save webmandesign/8578ca85da784bdcff9730deab548b1f to your computer and use it in GitHub Desktop.
WordPress theme file locator and loader.
<?php
/**
* File Class
*
* Helper class to locate and load files in child/parent
* theme only if they exist.
*
* Rename "Themeslug" according to your needs.
* Edit according to your needs...
*/
class Themeslug_File {
/**
* Locate file by its relative path.
*
* Searches child theme first, before falling back to parent theme.
* If the file is not found, returns an empty string.
*
* @param string $path_relative
*/
public static function get_path( $path_relative = '' ) {
$path_absolute = get_theme_file_path( $path_relative );
if ( ! file_exists( $path_absolute ) ) {
$path_absolute = '';
}
return $path_absolute;
}
/**
* Load a file using different PHP statements.
*
* @param string $path_relative
* @param string $statement
*/
public static function load( $path_relative = '', $statement = 'require' ) {
$path = self::get_path( $path_relative );
if ( ! empty( $path ) ) {
switch ( $statement ) {
case 'require':
require $path;
break;
case 'require_once':
require_once $path;
break;
case 'include':
include $path;
break;
case 'include_once':
include_once $path;
break;
default:
break;
}
}
}
}
@webmandesign
Copy link
Author

webmandesign commented Dec 8, 2018

WordPress theme file locator and loader

Rename Themeslug according to your needs (your WordPress theme slug).
Edit & share according to your needs...

How to use

Copy the file into your theme and load it in functions.php file with require get_template_directory() . '/class-file.php'; (or require get_template_directory() . '/path/to/class-file.php';).

To find the child/parent theme file path use Themeslug_File::get_path( 'relative/path/to/file.php' );. If the file does not exist, empty string is returned.

To load a child/parent theme file use Themeslug_File::load( 'relative/path/to/file.php', 'require' );. If the file does not exist, nothing is loaded. The require argument is the default value, so it can be committed, or replaced with require_once or include or include_once depending on your needs.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment